1import java.math.BigInteger; 2import java.security.MessageDigest; 3import java.security.NoSuchAlgorithmException; 4 5/** 6 * @author joymufeng 7 */ 8public class Md5 { 9 private static MessageDigest digester; 10 11 static { 12 try { 13 digester = MessageDigest.getInstance("MD5"); 14 }catch (NoSuchAlgorithmException e) { 15 e.printStackTrace(); 16 } 17 } 18 19 /** 20 * 将任意的字符串进行md5加密,并返回加密后的十六进制字符串。 21 * 需要注意,MessageDigest是非线程安全的,所以需要使用synchronized同步。 22 * @param str 待加密字符串 23 * @return 返回md5加密后的十六进制字符串 24 */ 25 public static String encrypt(String str) { 26 if (digester == null || str == null || str.length() == 0) { 27 return null; 28 } 29 30 synchronized (digester){ 31 try { 32 digester.update(str.getBytes("UTF-8")); 33 String s1 = new BigInteger(1, digester.digest()).toString(16); 34 //补齐BigInteger省略的前置0 35 return new String(new char[32 - s1.length()]).replace("\0", "0") + s1; 36 } catch (Exception e) { 37 //一般不会有异常抛出, 该死的Java受检异常,导致丑陋的代码 38 } 39 } 40 41 return null; 42 } 43}
Java生成十六进制的MD5加密字符串
Wesley13
2021-10-11
1134 0 0
点赞
收藏
评论区
加载中...