Extremely Serious

Month: March 2023

Checksum Using SHA-256 MessageDigest

//The data to be checksumed.
final var data = "Hello";
final MessageDigest md;
try {
    md = MessageDigest.getInstance("SHA-256");
    try (DigestInputStream dis = new DigestInputStream(
            //This can be replaced with FileInputStream.
            //The data just needs to be a File path.
            new ByteArrayInputStream(data.getBytes())
            , md)) {
        final var buffer = new byte[4096];
        int bytesRead;
        while ((bytesRead = dis.read(buffer)) != -1) {
            // Read the data into the buffer to update the digest
            md.update(buffer, 0, bytesRead);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    final var digest = md.digest();
    final var sb = new StringBuilder();
    for (final byte b : digest) {
        sb.append(String.format("%02x", b & 0xff));
    }
    System.out.println("Checksum: " + sb.toString());
} catch (NoSuchAlgorithmException e) {
    throw new RuntimeException(e);
}

Retrieving the X509 Certificate Information in Java

//This will hold the target leaf certificate.
Optional<Certificate> cert;

try {
    //Must hold the target URL.
    final var targetUrl = "https://www.google.com";
    final var httpsURL = new URL(targetUrl);
    final var connection = (HttpsURLConnection) httpsURL.openConnection();
    connection.connect();

    //Retrieve the first certificate. This is normally the leaf certificate.
    cert = Arrays.stream(connection.getServerCertificates()).findFirst();
} catch (IOException e) {
    throw new RuntimeException(e);
}

cert.ifPresent(cer -> {
    //Check if the instance of certificate is of type of X509Certificate.
    if(cer instanceof final X509Certificate x509) {
        System.out.println("Subject: " + x509.getSubjectX500Principal().getName());
        System.out.println("From: " + x509.getNotBefore());
        System.out.println("To: " + x509.getNotAfter());
        System.out.println("Duration: " + ChronoUnit.DAYS.between(LocalDate.now(), LocalDate.ofInstant(x509.getNotAfter().toInstant(),ZoneId.systemDefault())));
        System.out.println("\n");
    }
});