Java: SHA-256 hashing for integrity
A cryptographic hash function turns any input into a fixed-size digest. It is deterministic, one-way, and designed so that a tiny change in the input changes the digest unpredictably. SHA-256 produces 32 bytes, shown here as 64 hexadecimal characters.
Java
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
class Main {
static String hex(byte[] bytes) {
StringBuilder sb = new StringBuilder();
for (byte b : bytes) {
sb.append(String.format("%02x", b));
}
return sb.toString();
}
public static void main(String[] args) throws Exception {
MessageDigest sha = MessageDigest.getInstance("SHA-256");
String a = hex(sha.digest("abc".getBytes(StandardCharsets.UTF_8)));
String b = hex(sha.digest("abd".getBytes(StandardCharsets.UTF_8)));
System.out.println(a);
System.out.println(b);
System.out.println(MessageDigest.isEqual(a.getBytes(StandardCharsets.UTF_8), a.getBytes(StandardCharsets.UTF_8)));
}
}