Calculating SHA-1 hashes in Java and C#

前端 未结 2 479
谎友^
谎友^ 2021-02-06 05:50

Calculating SHA-1 hashes in Java and C#

I\'m trying to replicate the logic of a Java application within a C# application. Part of this involves generating an SHA-1 ha

相关标签:
2条回答
  • 2021-02-06 06:24

    your question and the answer were very useful to me, but I noticed that when the password has the character "0" hash codes generated are different, so I changed a little the code (in Java).

    for (int i = 0; i < hash.length; i++)
        {
            String hex = Integer.toHexString(hash[i]);
            if (hex.length() == 1) hex = "0" + hex;
            hex = hex.substring(hex.length() - 2);
            result += hex;
        }
    
    0 讨论(0)
  • 2021-02-06 06:32

    In the Java version, do not use b + 256; instead, use b & 255. The SHA-1 part is fine, this is just a matter of printing the output. Java's "byte" type is signed: it returns values between -128 and 127. To get the corresponding unsigned value, you must add 256 only if the value is negative.

    A bitwise AND with 255 (that's what "& 255" does) operates the proper conversion, which, at the binary level, is truncation of the value to its 8 least significant bits.

    0 讨论(0)
提交回复
热议问题