C#SHA-256与Java SHA-256.结果不同?

Ily*_*s I 3 .net c# java cryptography sha256

我想将一些Java中的代码转换为C#.

Java代码:

  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!");
  }
Run Code Online (Sandbox Code Playgroud)

当我尝试使用SimpleHash 类时,我得到了不同的哈希值

更新:

例如:

Java:byte [] hash = digest.digest(SALT); 生成(前6个字节):

[0] = 9
[1] = -95
[2] = -68
[3] = 64
[4] = -11
[5] = 53
....
Run Code Online (Sandbox Code Playgroud)

C#代码(类SimpleHash):string hashValue = Convert.ToBase64String(hashWithSaltBytes); hashWithSaltBytes有(前6个字节):

[0] 175 byte
[1] 209 byte
[2] 120 byte
[3] 74  byte
[4] 74  byte
[5] 227 byte
Run Code Online (Sandbox Code Playgroud)

dtb*_*dtb 7

String.getBytes方法编码字符串使用平台的默认字符集字节,而你链接的示例代码使用UTF-8.

试试这个:

digest.update(secret.getBytes("UTF-8"));
Run Code Online (Sandbox Code Playgroud)

其次,Integer.toHexString方法返回没有前导0的十六进制结果.