如题,一个工具类,直接MD5.compute("123456"); 即可计算一个字符串的MD5。
如需要其他Hash算法,如SHA1 SHA-256等,请查看https://blog.terrynow.com/2021/04/29/java-hash-tool-md5-sha1-sha256/
public class MD5 { public static String compute(String source) { String result = null; try { byte[] valueByte = source.getBytes(); MessageDigest md = MessageDigest.getInstance("MD5"); md.update(valueByte); result = toHex(md.digest()); } catch (NoSuchAlgorithmException e) { e.printStackTrace(); } return result; } // 将传递进来的字节数组转换成十六进制的字符串形式并返回 private static String toHex(byte[] buffer) { StringBuilder sb = new StringBuilder(buffer.length * 2); for (byte b : buffer) { sb.append(Character.forDigit((b & 0xf0) >> 4, 16)); sb.append(Character.forDigit(b & 0x0f, 16)); } return sb.toString(); } public static void main(String[] args) { //123456的MD5 输出e10adc3949ba59abbe56e057f20f883e System.out.println(MD5.compute("123456")); } }
文章评论