I need to convert a string to a byte[]. If that were it the task would be simple. I need to write it in C#, but I need it to act like Java.
There are two problems I'm seeing:
Endianness: Java stores things internally as Big Endian, while .NET is Little Endian by default.
Signedness: C# bytes are unsigned. Java bytes are signed.
How can I take a UTF-8 string, and get a byte[] that will match what it would in Java.
To give more context, I have these two functions (one in java, one in c#), they create different hashes, I suspect it's due to the difference in byte representation in .net vs java.
Java:
String key = "test";
String data = "test";
String algorithm = "HmacSHA1";
Charset charset = Charset.forName("utf-8");
SecretKeySpec signingKey = new SecretKeySpec(key.getBytes(), algorithm);
Mac mac = Mac.getInstance(algorithm);
mac.init(signingKey);
return new String(Base64.encodeBase64(mac.doFinal(data.getBytes(charset))), charset);
C#:
string key = "ed2ee2e0-65c1-11de-8a39-0800200c9a66";
string data = "test";
byte[] aKey = Encoding.UTF8.GetBytes(key);
byte[] aData = Encoding.UTF8.GetBytes(data);
HMACSHA1 oEncode = new HMACSHA1(aKey);
byte[] aBytes = oEncode.ComputeHash(aData);
return Convert.ToBase64String(aBytes);
No comments:
Post a Comment