0

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.

7
  • Maybe the problem is in endianness? Commented Dec 6, 2012 at 10:36
  • 4
    Did you see this? stackoverflow.com/questions/6843698/… Commented Dec 6, 2012 at 10:37
  • what is the value of bytes in both cases? Commented Dec 6, 2012 at 10:38
  • No i didn't find that .. let me check Commented Dec 6, 2012 at 10:42
  • 1
    If they have the same values... how are they different? Commented Dec 6, 2012 at 10:47

2 Answers 2

3

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();
    }
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.