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

I am using following code block to generate MD5 hashes:

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(), 0, 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;

}

When I run the above code segment with String data as [12, B006GQIIEM, MH-ANT2000], the output is a 31 character hash - 268d43a823933c9dafaa4ac0e756d6a.

Is there any problem with the MD5 hash function or there is some problem in the code above?

解决方案

The only issue in your code is when MSB is less than Ox10, the result hash string will only have 31 bytes, instead of 32 bytes, missing the leading zero.

Create your md5 string in this way:

byte messageDigest[] = m.digest();

hexString = new StringBuffer();

for (int i=0;i

String hex=Integer.toHexString(0xFF & messageDigest[i]);

if(hex.length()==1)

hexString.append('0');

hexString.append(hex);

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值