1、实现代码
import java.security.MessageDigest; import java.security.NoSuchAlgorithmException;public class SHA256Example {public static void main(String[] args) {String input = "Hello, World!"; // 要计算哈希的输入字符串try {// 获取 SHA-256 的 MessageDigest 实例MessageDigest digest = MessageDigest.getInstance("SHA-256");// 计算哈希值byte[] hashBytes = digest.digest(input.getBytes());// 将字节数组转换为十六进制字符串StringBuilder hexString = new StringBuilder();for (byte b : hashBytes) {// 将每个字节转为十六进制,并确保每个值为两位hexString.append(String.format("%02x", b));}// 输出结果System.out.println("SHA-256 Hash: " + hexString.toString());} catch (NoSuchAlgorithmException e) {e.printStackTrace();}} }