Search code examples
c#java.netsha1

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.


Solution

  • 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();
        }