MD5散列算法

MD5生成16位的字节,一个字节就是8个bit 8个二进制字符  2个16进制字符
所以用16进制来查看MD5的结果是32个字符

byte[] b = Md5Utils.md5sum("123");
    	System.out.println(b.length);
    	 String resultString = byteArrayToHexString(b);
    	 System.out.println(resultString);


输出
16
202CB962AC59075B964B07152D234B70

SHA-1比MD5的碰撞概率更低,  20位字节

 public static String byteArrayToHexString(byte[] b){  
        StringBuffer resultSb = new StringBuffer();  
        for (int i = 0; i < b.length; i++){  
            resultSb.append(byteToHexString(b[i]));  
        }  
        return resultSb.toString();  
    }  
      
    /** 将一个字节转化成十六进制形式的字符串     */  
    private static String byteToHexString(byte b){  
        int n = b;  
        if (n < 0)  
            n = 256 + n;  
        int d1 = n / 16;  
        int d2 = n % 16;  
        return hexDigits[d1] + hexDigits[d2];  
    }  
public static byte[] md5sum(String s) {
    MessageDigest d;
    try {
      d = MessageDigest.getInstance("MD5");
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException("MD5 algorithm not available!", e);
    }

    return d.digest(Bytes.toBytes(s));
  }

你可能感兴趣的:(MD5)