Chrome和IE返回不同的SHA哈希值

Chrome and IE return different SHA hashes

本文关键字:SHA 哈希值 IE 返回 Chrome      更新时间:2023-09-26

我写了一个网站,利用SHA-256哈希来验证用户的密码。这是一个相对不安全的设置,因为大多数用户将使用相同的用户名/密码。为了尽量保护它,我做了以下操作:

  1. 客户端向服务器请求一个新的盐
  2. 客户端使用此salt对密码进行散列
  3. 客户端将带盐的散列密码发送回服务器
  4. 服务器对实际密码进行散列并比较两者
下面是我的代码: c#

//Just for testing!
private static Dictionary<string, string> users = new Dictionary<string, string>() { { "User", "Password" } };
[HttpGet]
public HttpResponseMessage GetSalt()
{
   RNGCryptoServiceProvider secureRNG = new RNGCryptoServiceProvider();
   byte[] saltData = new byte[64];
   secureRNG.GetBytes(saltData);
   HttpResponseMessage response = new HttpResponseMessage();
   response.Content = new StringContent(System.Text.Encoding.Unicode.GetString(saltData), System.Text.Encoding.Unicode);
   return response;
}
[HttpGet]
public bool ValidateUser(string userName, string hashedPassword, string salt)
{
   SHA256Managed hash = new SHA256Managed();         
   if (users.ContainsKey(userName))
   {
       string fullPassword = salt + users[userName];
       byte[] correctHash = hash.ComputeHash(System.Text.Encoding.UTF8.GetBytes(fullPassword));
       if (hashedPassword.ToUpper() == BitConverter.ToString(correctHash).Replace("-",""))
       {
           return true;
       }
   }
   return false;
}
Javascript

$scope.login = function () {
    $http.get('api/Login').success(function (salt) {
        //Hash the password with the salt and validate
        var hashedPassword = sjcl.hash.sha256.hash(salt.toString().concat($scope.password));
        var hashString = sjcl.codec.hex.fromBits(hashedPassword);
        $http.get('api/Login?userName=' + $scope.userName + '&hashedPassword=' + hashString + '&salt=' + salt).success(function (validated) {
            $scope.loggedIn = validated;
        });
    });

此代码在Google Chrome上运行良好,但在Internet Explorer 11上不能运行。问题(如调试器中所见)是javascript生成的哈希值与c#生成的哈希值不同。

怀疑这与字符编码有关,但在网上没有找到太多证据来证明/反驳这个理论(或帮助解决一般问题)。如果有更好的方法来解决这个问题,我很高兴听到它,但我也想知道最初错误的原因。

为什么哈希值不同,我能做些什么来修复它?

IE不支持查询字符串中的Unicode字符。它也不喜欢ASCII中的一些"特殊"字符。即使它正确地接受它们,并正确地执行哈希,当你运行这段代码时,来自IE的盐是"???????",而来自Chrome的盐是正确的字符串。

简单的解决方法是将salt的字符集限制为大写、小写和数字。使用此方法,两个浏览器都会给出正确的哈希值。