SHAUtils工具类
使用SHA-256算法
public class SHAUtils {
public static String SHA256(byte[] bytes) throws NoSuchAlgorithmException {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(bytes);
return bytesToHex(hash);
}
private static String bytesToHex(byte[] bytes) {
StringBuilder builder = new StringBuilder();
for (byte b : bytes) {
builder.append(String.format("%02x", b));
}
return builder.toString();
}
}
测试类
public class GetFileHash {
public static void main(String[] args) throws IOException, NoSuchAlgorithmException {
String filePath = "D:\\file\\1.png";
// String filePath = "D:\\file\\实习生合同.pdf";
byte[] bytesArray= Files.readAllBytes(new File(filePath).toPath());
String s = SHAUtils.SHA256(bytesArray);
System.out.println(s);
System.out.println(ObjectUtil.equals("3649db81a9a9d921048cd584c3fc7abaea8b850c188502e3aeee7510bf601634",s));
}
}