java没签名,如何在Java中获取未签名的md5哈希

I am using consuming a C# web services and one of the parameters is sending a md5 hash. Java creates MD5 hash with signed (contains negative number in the byte array) and C# generates unsigned (contains no negative number in the byte array).

I have gone through multiple similar question in Stack Overflow but did not find any to my satisfaction.

All I need is unsigned byte array similar to the one c# generates. I have tried using BigInteger but I need it in an unsigned byte array since I need do further processing after that. BigInteger gives me one single integer and using tobytearray() still has negative numbers.

If I have to do 2 complement, then how can I do that. Then I can loop through the byte array and convert negative number to positive number.

I am using the following Java code for generating MD5 hash:

String text = "abc";

MessageDigest md = MessageDigest.getInstance("MD5");

byte[] md5hash = new byte[32];

try {

md.update(text.getBytes("utf-8"), 0, text.length());

} catch (UnsupportedEncodingException e) {

// TODO Auto-generated catch block

e.printStackTrace();

}

md5hash = md.digest();

解决方案

Java bytes are signed numbers, but that only means that when considering a byte (which is a sequence of 8 bits) as a number, Java treats one of the bits as a sign bit, whereas other language read the same sequence of bits as an unsigned number, containing no sign bit.

The MD5 algorithm is a binary algorithm that transforms a sequence of bits (or bytes) into another sequence of bits (or bytes). The way Java does that is the same as the way any other language does it. It's only when displaying the bytes as numbers that you'll get different outputs depending on the way the language transforms bytes into numbers.

So the short answer is, send an MD5 hash generated using Java to a C# program, and it will work fine.

If you want to display the byte array in Java as unsigned numbers, just use the following code:

for (byte b : bytes) {

System.out.println(b & 0xFF);

}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值