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

标签 c# java hash sha1

在 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 fa
Java 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/

相关文章:

java - 受信任的证书条目不受密码保护 java

java - 使用 TreeTranslator 重命名不适用于 Kotlin 的函数

arrays - 如何从 Perl 中的数组中获取哈希值?

c# - 无法加载 oramts.dll

c# - asp.net Entity Framework <%# Bind ("linkedTable.Field") %>

c# - 基于项目权重合并多个列表的高效方法

security - 哈希和 'brute-force' 排列

c# - 将多个 Include() 与嵌套 Select() 结合使用时出现 EntityCommandExecutionException

Java - 如何确保可调用线程返回的数组的可见性

java - 如何开发交通执照号码的哈希函数?