Java vs C# BigInteger Producing different values

I made my first post on SO to ask this question but was quickly downvoted to death by all the points nazis. After rewriting the question a couple of times to try and appease them, I have had no replies, so I assume nobody is interested in anything other than downvoting over there. So here I am on sitepoint giving it another go.

I am having some trouble with producing the same BigInteger value in C# as I get in Java. In both languages the BigIntegers are created from an array of bytes which hold the same values, in the same order.

The Java BigInteger is created like so:

BigInteger hashnum = new BigInteger(1, md.digest());
And produces: 79054595997078811232777738014361687045908459940911070866043475968067897954324

md.digest() returns an array with the following byte values in both languages: {-73, 97, 1, -64, 23, 38, 69, 95, 107, 122, 119, -122, -99, -92, 47, 8, -118, 70, 119, 98, 64, -1, -70, 36}

I am aware of the difference between java and c# expecting big vs little endian ordering of the byte array, but both reversing and not reversing the array in C# provides a different result than the result I get in Java. To clarify, the resulting BigInteger in java is the intended result and I cannot seem to match it in C#.

My C# code:

With adding 0 byte to end, but not reversing the byte array

sbyte[] hashSBytes = md.digest();
if ((hashSBytes[hashSBytes.Length - 1] & 0x80) != 0)
{
   Array.Resize<sbyte>(ref hashSBytes, hashSBytes.Length + 1);
}
BigInteger hashnum = new BigInteger((byte[])(object)hashSBytes);

The BigInteger has a value of 92590942655695057524171612499701658178022831645290183610636811349839086444983

With adding 0 byte AND reversing the byte array

sbyte[] hashSBytes = md.digest();
Array.Reverse(hashSBytes);
if ((hashSBytes[hashSBytes.Length - 1] & 0x80) != 0)
{
   Array.Resize<sbyte>(ref hashSBytes, hashSBytes.Length + 1);
}

BigInteger hashnum = new BigInteger((byte)(object)hashSBytes);
The BigInteger has a value of 82944647536515285715130977031103916663496217450446852247301410452203227690188

Check out my answer to your question on Stack Overflow: https://stackoverflow.com/questions/45470851/java-vs-c-sharp-biginteger-producing-different-values

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.