Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# SHA-256 vs. Java SHA-256. Different results?

I want to convert a some code which is in Java to C#.

Java Code:

  private static final byte[] SALT = "NJui8*&N823bVvy03^4N".getBytes();

  public static final String getSHA256Hash(String secret)
  {
    try {
      MessageDigest digest = MessageDigest.getInstance("SHA-256");
      digest.update(secret.getBytes());
      byte[] hash = digest.digest(SALT);
      StringBuffer hexString = new StringBuffer();
      for (int i = 0; i < hash.length; i++) {
        hexString.append(Integer.toHexString(0xFF & hash[i]));
      }
      return hexString.toString();
    } catch (NoSuchAlgorithmException e) {
      e.printStackTrace();
    } 
    throw new RuntimeException("SHA-256 realization algorithm not found in JDK!");
  }

When I tried to use the SimpleHash class I got different hashs

UPDATE:

For example:

Java: byte[] hash = digest.digest(SALT); generates (first 6 bytes):

[0] = 9
[1] = -95
[2] = -68
[3] = 64
[4] = -11
[5] = 53
....

C# code (class SimpleHash): string hashValue = Convert.ToBase64String(hashWithSaltBytes); hashWithSaltBytes has (first 6 bytes):

[0] 175 byte
[1] 209 byte
[2] 120 byte
[3] 74  byte
[4] 74  byte
[5] 227 byte
like image 578
Ilyas I Avatar asked Dec 13 '22 10:12

Ilyas I


2 Answers

The String.getBytes method encodes the string to bytes using the platform's default charset, whereas the example code you linked uses UTF-8.

Try this:

digest.update(secret.getBytes("UTF-8"));

Secondly, the Integer.toHexString method returns the hexadecimal result with no leading 0s.

like image 100
dtb Avatar answered Dec 28 '22 22:12

dtb


The C# code you link to also uses salt - but the Java code does not. If you use salt with once, but not the other, then the results will be (and should be!) different.

like image 30
Cocowalla Avatar answered Dec 28 '22 21:12

Cocowalla