生成MD5只有31位如何解决?

生成MD5有时只有31位如何解决?

public static String toMd5(File file) {
        String value = null;
        byte[] encrypt;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            encrypt = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte t : encrypt) {
                sb.append(Integer.toHexString(t & 0xFF));
            }
            value = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

在上面代码中

Integer.toHexString(t & 0xFF)会将首位为0的两位数转成字符串时,只保留一位,这就造成生成MD5有时会变成31位

解决办法:

public static String toMd5(File file) {
        String value = null;
        byte[] encrypt;
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            MappedByteBuffer byteBuffer = in.getChannel().map(FileChannel.MapMode.READ_ONLY, 0, file.length());
            MessageDigest md5 = MessageDigest.getInstance("MD5");
            md5.update(byteBuffer);
            encrypt = md5.digest();
            StringBuilder sb = new StringBuilder();
            for (byte t : encrypt) {
                String s = Integer.toHexString(t & 0xFF);
                if (s.length() == 1) {
                    s = "0" + s; // 注意此行,如果只有一位,在首位加0
                }
                sb.append(s);
            }
            value = sb.toString();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return value;
    }

 

 
posted @ 2020-04-27 10:07  二次元的程序猿  阅读(1071)  评论(0编辑  收藏  举报