Freak
Freak

Reputation: 6873

SHA1 hash computation not returing same result for java and c#

I am computing hash in my .net and Java application.But I got a problem when they gave me result because both are giving different results.While searching about this problem, I found these questions
question 1 and question 2 so applied there according tho their answers but unfortunately i didn't get success.I also tried UTF-8 and UTF-16LE but result was again not same.
Now I am stuck and want to know why it is happening and How can I solve this
My code snippet is given below
.Net

byte[] buffer2 = new SHA1CryptoServiceProvider().ComputeHash(bytes);


Java

MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        byte[] buffer2 = sha1.digest(bytes);

Any help would be greatly appreciated.

Upvotes: 0

Views: 4183

Answers (2)

Itay Karo
Itay Karo

Reputation: 18286

So just to recap my comment as an answer. See this: Calculating SHA-1 hashes in Java and C#
Basically - Java bytes are signed while C# bytes are not. The internal representation of both results will be the same but printing them will yield different results unless you do proper conversions.

Upvotes: 2

Asuka
Asuka

Reputation: 66

I think problem is that in C# byte is unsigned type, and in java it not.

This 2 codes works equally:

    public static void main(String[] args) throws NoSuchAlgorithmException {
        MessageDigest sha1 = MessageDigest.getInstance("SHA1");
        byte[] bytes = new byte[] { 1, 2, 10 };
        byte[] buffer2 = sha1.digest(bytes);
        for(byte b : buffer2){
            System.out.println(b);
        }
    }

    static void Main(string[] args)
    {
        var bytes = new byte[] { 1, 2, 10 };
        var buffer = new SHA1CryptoServiceProvider().ComputeHash(bytes);
        foreach (var b in buffer)
        {
            Console.WriteLine((sbyte)b); //attention to cast           
        }
        Console.Read();
    }

Upvotes: 3

Related Questions