title: Java SHA1 hash to base64 : unsigned bytes?
body: <p>I am trying to <strong>hash</strong> a value (<strong>SHA1</strong>) in both <strong>C#</strong> and <strong>Java</strong>, and then return a <strong>base64</strong> representation. I get 2 different results.</p>
  
  <p>I know this is because Java uses <strong>signed bytes</strong> while C# <strong>doesn't</strong>.</p>
  
  <p><strong>C# version</strong> :</p>
  
  <pre><code>static public string toSHA1(string toEncrypt)
  {
      return toSHA1(toEncrypt, new UTF8Encoding());
  }
  
  static public string toSHA1(string toEncrypt, Encoding encoding)
  {
      String salt = "fE4wd#u*d9b9kdKszgè02ep5à4qZa!éi6";
      SHA256Managed sha256hasher = new SHA256Managed();
      byte[] hashedDataBytes = sha256hasher.ComputeHash(encoding.GetBytes(toEncrypt + salt));
      return Convert.ToBase64String(hashedDataBytes);
  }
  </code></pre>
  
  <p><strong>Java version</strong> :</p>
  
  <pre><code>public static String toSHA1(String toEncrypt) {
      return toSHA1(toEncrypt, "UTF-8");
  }
  
  public static String toSHA1(String toEncrypt, String encoding) {
      String salt = "fE4wd#u*d9b9kdKszgè02ep5à4qZa!éi6";
      String res = null;
      toEncrypt = toEncrypt + salt;
      try {
          byte[] dataBytes = toEncrypt.getBytes(encoding);
          MessageDigest md = MessageDigest.getInstance("SHA-1");
          res = Base64.encodeBytes(md.digest(dataBytes));
      } catch (NoSuchAlgorithmException e) {
          e.printStackTrace();
      } catch (UnsupportedEncodingException e) {
          e.printStackTrace();
      }
      return res;
  }
  </code></pre>
  
  <p>I can't manage to find a solution to get the correct <strong>base64</strong> result using <strong>Java</strong>.</p>
  
  <p>Converting <strong>signed</strong> values to <strong>unsigned</strong> ones forces the use of <code>int</code> data type, but as soon as I put it in a <code>byte</code> data type, I get my <strong>signed</strong> bytes back...</p>
  
  <p><code>Base64.encodeBytes</code> is waiting for a <code>byte</code> array, so is there any way I can pass an <strong>unsigned</strong> <code>byte</code> array to this method ? What can I do with that <code>int</code> array ? :</p>
  
  <pre><code>int[] dataInt = new int[dataBytes.length];
  // signed to unsigned
  for (int i=0; i&lt;dataBytes.length; i++)
  {
      dataInt[i] = (dataBytes[i] &amp; 0xFF);
  }
  </code></pre>
  
  <p>I <strong>can't</strong> modify the <strong>C#</strong> version, I have to adapt the <strong>Java</strong> version to give the same results.</p>