加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

MD5在Java中生成31个字符的散列

发布时间:2020-12-14 16:37:55 所属栏目:Java 来源:网络整理
导读:我正在使用以下代码块来生成MD5哈希值: public static String encode(String data) throws Exception { /* Check the validity of data */ if (data == null || data.isEmpty()) { throw new IllegalArgumentException("Null value provided for " + "MD5 E
我正在使用以下代码块来生成MD5哈希值:
public static String encode(String data) throws Exception {

    /* Check the validity of data */
    if (data == null || data.isEmpty()) {
        throw new IllegalArgumentException("Null value provided for "
                + "MD5 Encoding");
    }

    /* Get the instances for a given digest scheme MD5 or SHA */
    MessageDigest m = MessageDigest.getInstance("MD5");

    /* Generate the digest. Pass in the text as bytes,length to the
     * bytes(offset) to be hashed; for full string pass 0 to text.length()
     */
    m.update(data.getBytes(),data.length());

    /* Get the String representation of hash bytes,create a big integer
     * out of bytes then convert it into hex value (16 as input to
     * toString method)
     */
    String digest = new BigInteger(1,m.digest()).toString(16);

    return digest;
}

当我使用String数据运行上述代码段[12,B006GQIIEM,MH-ANT2000]时,输出是一个31个字符的散列 – 268d43a823933c9dafaa4ac0e756d6a.

MD5哈希函数有什么问题,或者上面的代码有一些问题吗?

解决方法

您的代码中唯一的问题是当 MSB小于Ox10时,结果散列字符串将只有31个字节,而不是32个字节,缺少前导零.

以这种方式创建你的md5字符串:

byte messageDigest[] = m.digest();

            hexString = new StringBuffer();
            for (int i=0;i<messageDigest.length;i++) {
                String hex=Integer.toHexString(0xFF & messageDigest[i]);
                if(hex.length()==1)
                    hexString.append('0');

                hexString.append(hex);
            }

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读