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

标签 c# java .net 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!");
  }

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

更新:

例如:

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

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

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

[0] 175 byte
[1] 209 byte
[2] 120 byte
[3] 74  byte
[4] 74  byte
[5] 227 byte

最佳答案

String.getBytes method使用平台的默认字符集将字符串编码为字节,而您链接的示例代码使用 UTF-8。

试试这个:

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

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

关于C# SHA-256 与 Java SHA-256。不同的结果?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7095664/

相关文章:

java - 状态管理-【切换状态,重玩游戏】

Java 从包含空格的字节数组创建字符串

c# - 从 https 页面链接

c# - IList 必须是有限的吗?

c# - 有没有办法在不发出许多行 .Count() 的情况下获取匹配多个不同条件的行数

C# - 为扩展方法提供类型信息

java - 求二的幂的最快方法?

.net - 在您的应用程序中实现插件的设计模式?

c# - Assembly.LoadFrom 和依赖项

c# - 如何在 ASP.NET 5 RC 1 中使用 JavaScriptSerializer?