开发者

String to byte[] - c# act like java [duplicate]

开发者 https://www.devze.com 2023-04-11 03:52 出处:网络
This question already has answers here: Closed 11 years ago. Possible Duplicate: .NET String to byte Array C#
This question already has answers here: Closed 11 years ago.

Possible Duplicate:

.NET String to byte Array C#

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");
Se开发者_如何学运维cretKeySpec 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);


Just use:

byte[] bytes = Encoding.UTF8.GetBytes("SomeString");

There are a few notes though:

  1. There is no such thing as "UTF-8" string in .NET: all strings are Unicode (UCS-2).
  2. There is no big endian/little endian byte order in UTF-8, the order of bytes is defined by format. Check RFC-2279 for details.

Why do you care if byte is signed or not?


As was commented above, the behaviour is exactly the same for byte endianness. Signed vs. unsigned isn't really a factor here, either.

Just use this:

byte[] bytes = Encoding.UTF8.GetBytes("my string");

And you should be fine.

If you explain why you need something other than this case, I might be able to help further.


It has been quite some time since I played in a heterogenous environment, but I am not convinced the signed versus unsigned should make a huge difference. If I am correct, the ordering of the array is the big issue.

There are two solutions (potential solutions?):

  1. Flip the array in .NET using Array.Reverse()
  2. use little endian in Java

Either should solve the ordering problem.

0

精彩评论

暂无评论...
验证码 换一张
取 消