平时写程序时候,经常需要计算哈希值(MessageDigest摘要),如MD5、SHA1、SHA256等等,不妨做一个工具类,要用到的时候,一个方法调用就可以了,方便省事,下面是我使用的工具类,原生Java,无依赖。
Javascript版本实现哈希算法,请查看:https://blog.terrynow.com/2021/05/05/javascript-html-hash-tool-md5-sha1-sha256/
HashUtil.java
要用的时候,直接HashUtil.sha1("123456");HashUtil.md5("123456");HashUtil.hash("123456", "SHA-512");
public class HashUtil {
public static void main(String[] args) {
//SHA1
System.out.println(HashUtil.sha1("123456"));//7c4a8d09ca3762af61e59520943dc26494f8941b
//SHA-256
System.out.println(HashUtil.sha256("123456"));//8d969eef6ecad3c29a3a629280e686cf0c3f5d5a86aff3ca12020c923adc6c92
//MD5
System.out.println(HashUtil.md5("123456"));//e10adc3949ba59abbe56e057f20f883e
//可以直接指定算法,如:SHA1、SHA-224、SHA-256、SHA-284、SHA-512、MD5
System.out.println(HashUtil.hash("123456", "SHA-512"));
System.out.println(HashUtil.hash("123456", "MD5"));
}
public static String sha1(String source) {
return hash(source, "SHA1");
}
public static String md5(String source) {
return hash(source, "MD5");
}
public static String sha256(String source) {
return hash(source, "SHA-256");
}
public static String hash(String source, String algorithm) {
if (source == null || source.length() == 0) {
return null;
}
try {
MessageDigest messageDigest = MessageDigest.getInstance(algorithm);
messageDigest.update(source.getBytes(StandardCharsets.UTF_8));
return bytesToHex(messageDigest.digest());
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
private static final byte[] HEX_ARRAY = "0123456789abcdef".getBytes(StandardCharsets.US_ASCII);
/**
* 把bytes转化成十六进制string
*/
private static String bytesToHex(byte[] bytes) {
byte[] hexChars = new byte[bytes.length * 2];
for (int j = 0; j < bytes.length; j++) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = HEX_ARRAY[v >>> 4];
hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
}
return new String(hexChars, StandardCharsets.UTF_8);
}
}
文章评论