为什么我的PHP相当于C#SHA256哈希散列SHA256Managed [英] Why isn't my PHP SHA256 hash equivalent to C# SHA256Managed hash

查看:753
本文介绍了为什么我的PHP相当于C#SHA256哈希散列SHA256Managed的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么不是这些相同



PHP的:

  $哈希散列=('SHA256',$用户数据['盐']哈希('SHA256',$密码)。); 



C#



 公共静态字符串ComputeHash(明文字符串,字符串盐)
{
//将纯文本转换成字节数组。
字节[] = plainTextBytes Encoding.UTF8.GetBytes(明文);
字节[] = saltBytes Encoding.UTF8.GetBytes(盐);

SHA256Managed哈希=新SHA256Managed();盐

//计算哈希值。
字节[] = plainHash hash.ComputeHash(plainTextBytes);

字节[] = CONCAT新的字节[plainHash.Length + saltBytes.Length];

System.Buffer.BlockCopy(saltBytes,0,CONCAT,0,saltBytes.Length);
System.Buffer.BlockCopy(plainHash,0,CONCAT,saltBytes.Length,plainHash.Length);

字节[] = tHashBytes hash.ComputeHash(CONCAT);

//转换结果转换为base64编码字符串。
串散列值= Convert.ToBase64String(tHashBytes);

//返回结果。
返回散列值;
}


解决方案

C#是输出一个base64 ecoded串,和PHP的输出十六进制的数字。一个更好的比较可能是参数真实传递给PHP的散列函数的base64结果的末尾:

  $哈希= BASE64_ENCODE(
哈希('SHA256',$用户数据['盐']哈希('SHA256',$密码),真)
);


Why aren't these the same?

php:

    $hash = hash('sha256', $userData['salt'] . hash('sha256', $password) );

c#

    public static string ComputeHash(string plainText, string salt)
    {
        // Convert plain text into a byte array.
        byte[] plainTextBytes = Encoding.UTF8.GetBytes(plainText);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);

        SHA256Managed hash = new SHA256Managed();

        // Compute hash value of salt.
        byte[] plainHash = hash.ComputeHash(plainTextBytes);

        byte[] concat = new byte[plainHash.Length + saltBytes.Length];

        System.Buffer.BlockCopy(saltBytes, 0, concat, 0, saltBytes.Length);
        System.Buffer.BlockCopy(plainHash, 0, concat, saltBytes.Length, plainHash.Length);

        byte[] tHashBytes = hash.ComputeHash(concat);

        // Convert result into a base64-encoded string.
        string hashValue = Convert.ToBase64String(tHashBytes);

        // Return the result.
        return hashValue;
    }

解决方案

C# is outputting a base64 ecoded string, and PHP is outputting a number in hex. A better comparison might be to pass the parameter true to the end of the hash function of PHP and base64 the result:

 $hash = base64_encode(
           hash('sha256', $userData['salt'] . hash('sha256', $password), true )
         );

这篇关于为什么我的PHP相当于C#SHA256哈希散列SHA256Managed的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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