Java使用MD5加密,生成的密文长度只有31位
迷茫
迷茫 2017-04-17 17:43:36
0
1
827

在使用MD5加密时,生成的密文长度只有31位,该怎么解决?

代码如下:

public static String toMd5(String str) {
        String re = null;
        byte encrypt[];
        try {
            byte[] tem = str.getBytes();
            MessageDigest md5 = MessageDigest.getInstance("md5");
            md5.reset();
            md5.update(tem);
            encrypt = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte t : encrypt) {
                sb.append(Integer.toHexString(t & 0xFF));
            }
            re = sb.toString();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return re;
    }

比如加密admin,结果如图:

正常的32位加密结果为:21232f297a57a5a743894a0e4a801fc3
而我的代码加密结果为:21232f297a57a5a743894ae4a801fc3

正常的第23位的“0”不见了,求问大神产生的原因是什么?该如何解决?

迷茫
迷茫

业精于勤,荒于嬉;行成于思,毁于随。

reply all(1)
左手右手慢动作

The problem lies in this sentence: Integer.toHexString(t & 0xFF)Integer.toHexString(t & 0xFF)

t14时,十六进制就是0e,转化成字符串会忽略掉前导零。

改一下就行了:

String s = Integer.toHexString(t & 0xFF);
if (s.length() == 1) {
    s = "0" + s;
}

另外,md5

When t is 14, the hexadecimal value is 0e, and leading zeros will be ignored when converted into a string. #🎜🎜# #🎜🎜# Just change it: #🎜🎜# rrreee #🎜🎜#In addition, md5 is not an encryption algorithm. It calculates the message digest and can be used to verify data integrity. #🎜🎜#
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template