title: String to byte[] - c# act like java
body: <blockquote>
    <p><strong>Possible Duplicate:</strong><br>
    <a href="https://stackoverflow.com/questions/472906/net-string-to-byte-array-c">.NET String to byte Array C#</a>  </p>
  </blockquote>
  
  
  
  <p>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.</p>
  
  <p>There are two problems I'm seeing:</p>
  
  <p>Endianness: Java stores things internally as Big Endian, while .NET is Little Endian by default.</p>
  
  <p>Signedness: C# bytes are unsigned. Java bytes are signed.</p>
  
  <p>How can I take a UTF-8 string, and get a byte[] that will match what it would in Java.</p>
  
  <p>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:</p>
  
  <pre><code>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);
  </code></pre>
  
  <p>C#:</p>
  
  <pre><code>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);
  </code></pre>