如何在 Java 中获取未签名的 md5 哈希 [英] How to get unsigned md5 hash in Java

查看:71
本文介绍了如何在 Java 中获取未签名的 md5 哈希的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 C# Web 服务,其中一个参数是发送 md5 哈希.Java 用有符号(字节数组中包含负数)创建 MD5 哈希,C# 生成无符号(字节数组中不包含负数).

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).

我在 Stack Overflow 中遇到了多个类似的问题,但没有找到任何让我满意的问题.

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

我需要的是类似于 c# 生成的无符号字节数组.我曾尝试使用 BigInteger,但我需要在无符号字节数组中使用它,因为在那之后我需要做进一步的处理.BigInteger 给我一个整数,使用 tobytearray() 仍然有负数.

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.

如果我必须做2个补码,那我该怎么做.然后我可以遍历字节数组并将负数转换为正数.

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.

我使用以下 Java 代码生成 MD5 哈希:

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 字节是有符号数,但这仅意味着当将一个字节(它是一个 8 位的序列)视为一个数字时,Java 将其中一个位作为符号位,而其他语言读取的位序列与无符号数相同,不包含符号位.

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.

MD5 算法是一种二进制算法,它将一个位(或字节)序列转换为另一个位(或字节)序列.Java 这样做的方式与任何其他语言的方式相同.只有将字节显示为数字时,您才会根据语言将字节转换为数字的方式获得不同的输出.

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.

所以简短的回答是,将使用 Java 生成的 MD5 哈希发送到 C# 程序,它会正常工作.

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

如果要在Java中将字节数组显示为无符号数,只需使用以下代码:

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);
}

这篇关于如何在 Java 中获取未签名的 md5 哈希的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆