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 byte
s 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.
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.
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:
-73
is 183
in .NetSo 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 ?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With