//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);
}
Leave a Reply