Chrome和IE返回不同的SHA哈希值
我写了一个网站,利用SHA-256哈希来验证用户的密码。 这是一个相对不安全的设置,因为大多数用户将拥有相同的用户名/密码。 为了尽量保护它,我做了以下工作:
这是我的代码:
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;
        });
    });
此代码在谷歌浏览器上正常工作,但不在Internet Explorer 11上。问题(如调试器中所示)是由JavaScript生成的哈希与由C#生成的哈希不同。
我怀疑这与字符编码有关,但在网上找不到证明/反驳这个理论的东西(或者总体上帮助解决这个问题)。 如果有更好的方法来解决这个问题,我很乐意听到这个消息,但是也想理解原始错误的原因。
为什么哈希值不同,我能做些什么来修复它?
IE浏览器不喜欢在查询字符串中的Unicode字符。 它也不喜欢ASCII的一些“特殊”字符。 即使它正确地接受它们,并正确执行散列,但在运行此代码时,salt是“???????” 来自IE浏览器时,以及来自Chrome的正确字符串。
简单的解决方法是仅限盐的字符集为大写,小写和数字。 使用这种方法,两个浏览器都给出了正确的散列。
链接地址: http://www.djcxy.com/p/20949.html