C#SHA-256与Java的SHA-256。不同的结果? [英] C# SHA-256 vs. Java SHA-256. Different results?

查看:2201
本文介绍了C#SHA-256与Java的SHA-256。不同的结果?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要转换一些code这是Java到C#。

Java的code:

 私有静态最后byte []的盐=NJui8 *放大器; N823bVvy03 ^ 4N.getBytes();

  公共静态最后弦乐getSHA256Hash(字符串秘密)
  {
    尝试 {
      消息摘要摘要= MessageDigest.getInstance(SHA-256);
      digest.update(secret.getBytes());
      byte []的哈希值= digest.digest(SALT);
      StringBuffer的十六进制串=新的StringBuffer();
      的for(int i = 0; I< hash.length;我++){
        hexString.append(Integer.toHexString(0xFF的&放大器;哈希[我]));
      }
      返回hexString.toString();
    }赶上(抛出:NoSuchAlgorithmException E){
      e.printStackTrace();
    }
    抛出新的RuntimeException(SHA-256算法的实现不是在JDK中找到!);
  }
 

当我试图用的的SimpleHash类我得到了不同的hashs

更新:

例如:

Java的:byte []的哈希值= digest.digest(SALT); 生成(前6个字节):

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

C#code(类SimpleHash): 字符串的散列值= Convert.ToBase64String(hashWithSaltBytes); hashWithSaltBytes有(前6个字节):

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

解决方案

的的 String.getBytes方法 EN codeS的字符串使用平台的默认字符集的字节,而你链接的例子code使用UTF-8。

试试这个:

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

其次,整数.toHexString方法返回十六进制的结果,没有前导零。

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

解决方案

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.

这篇关于C#SHA-256与Java的SHA-256。不同的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆