gpt4 book ai didi

c# - 在 Java 和 C# 中计算 SHA-1 哈希

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:37:43 24 4
gpt4 key购买 nike

在 Java 和 C# 中计算 SHA-1 哈希值

我正在尝试在 C# 应用程序中复制 Java 应用程序的逻辑。其中一部分涉及生成密码的 SHA-1 散列。不幸的是,我无法从 Java 和 C# 获得相同的结果。

C# Output  : 64  0a  b2 ba e0 7b  ed c4 c1 63  f6 79  a7 46  f7 ab 7f  b5 d1 faJava Output: 164 10a b2 ba e0 17b ed c4 c1 163 f6 179 a7 146 f7 ab 17f b5 d1 fa 

To try and figure out what is happening I've been using the Debugger in Eclipse and Visual Studio.

1. Check values of byte[] key:    Java: { 84, 101, 115, 116 }    C#  : { 84, 101, 115, 116 }2. Check value of byte[] hash:    Java: { 100 10 -78 -70 -32 123 ... }    C#  : { 100 10  78 186 224 123 ... }

I've read the other posts on this topic, which largely refer to input string encoding, but these don't seem to have helped me. My guess would be that this is something to do with signed vs. unsigned bytes but I'm not making much progress down this track. Any help will be greatly appreciated.

Thanks,

Karle


Java Version:

public void testHash() {

String password = "Test";

byte[] key = password.getBytes();

MessageDigest md = MessageDigest.getInstance("SHA-1");

byte[] hash = md.digest(key);

String result = "";
for ( byte b : hash ) {
result += Integer.toHexString(b + 256) + " ";
}

System.out.println(result);

}

C#版本:

public void testHash() {

String password = "Test";

byte[] key = System.Text.Encoding.Default.GetBytes(password);

SHA1 sha1 = SHA1Managed.Create();

byte[] hash = sha1.ComputeHash(key);

String result;
foreach ( byte b in hash ) {
result += Convert.ToInt32(b).ToString("x2") + " ";
}

Console.WriteLine(result);

}

最佳答案

在Java版本中,不要使用b + 256;相反,请使用 b & 255。 SHA-1 部分没问题,这只是打印输出的问题。 Java 的“byte”类型是有符号的:它返回 -128 到 127 之间的值。要获得相应的无符号值,您必须添加 256仅当值为负时。

按位与 255(这就是“& 255”所做的)进行正确的转换,在二进制级别,将值截断为其 8 个最低有效位。

关于c# - 在 Java 和 C# 中计算 SHA-1 哈希,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6843698/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com