Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java BigInteger to byte array equivalent in .NET

I'm working on an integration with a partner that uses Java's BigInteger to generate a byte array as the key for a simple encryption algorithm. I'm trying to find the equivalent .NET code without much luck.

The Java code they're using is:

String keyString = "48B734DA47388C656913C9BF5146E186";
byte key[] = new BigInteger(keyString, 16).toByteArray();

which yields the following byte array:

[72, -73, 52, -38, 71, 56, -116, 101, 105, 19, -55, -65, 81, 70, -31, -122]

This alone is troubling because bytes in .NET range from 0-255 so the negative values are out of range.

The closest .NET code I came up with is:

string keyString = "48B734DA47388C656913C9BF5146E186";
byte[] key = BigInteger.Parse(keyString, NumberStyles.HexNumber).ToByteArray();

which yields the following byte array:

[134, 225, 70, 81, 191, 201, 19, 105, 101, 140, 56, 71, 218, 52, 183, 72]

At this point, I'm thinking a .NET equivalent simply isn't possible - especially because of the negative byte values.

I look forward to everyone's thoughts.

like image 229
rjygraham Avatar asked Dec 15 '22 10:12

rjygraham


2 Answers

Using the LINQ method I4V offered in the comments solves it handily.

  sbyte[] key = BigInteger.Parse(keyString, NumberStyles.HexNumber).ToByteArray().Reverse().Select(x => (sbyte)x).ToArray();

That will get you the array you want. .NET uses unsigned bytes by default, whereas Java uses signed bytes by default. They have the same bit representation, so, depending on what you're doing with it, it may not actually matter which one is used, but, if you want a truly equivalent output in .NET, you'll need to use sbytes instead of bytes, as simply using byte means different things between the two languages.

like image 190
Mike Precup Avatar answered Dec 25 '22 04:12

Mike Precup


When I compare the 2 result from Java :

[72, -73, 52, -38, 71, 56, -116, 101, 105, 19, -55, -65, 81, 70, -31, -122]

from .Net

[134, 225, 70, 81, 191, 201, 19, 105, 101, 140, 56, 71, 218, 52, 183, 72]

I can tell that:

  1. They seem alike - .Net is just in revers order (A result of java's internal representation being Big Endian).
  2. In .Net result, there are no negative numbers.
  3. Comparing the result in reverse order show that -73 is 183 in .Net

So I think we can say that the result are the same, but need to check that the Endianness is the same and that signs are maintained.

Can you show the code that print those result ?

like image 35
Mzf Avatar answered Dec 25 '22 03:12

Mzf