To hash a string, use the built-in MessageDigest class:
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
import java.math.BigInteger;
public class CryptoHash {
public static void main(String[] args) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance("SHA-256");
String text = "Text to hash, cryptographically.";
// Change this to UTF-16 if needed
md.update(text.getBytes(StandardCharsets.UTF_8));
byte[] digest = md.digest();
String hex = String.format("%064x", new BigInteger(1, digest));
System.out.println(hex);
}
}
In the snippet above, digest
contains the hashed string and hex
contains a hexadecimal ASCII string with left zero padding.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…