PHP等效密码散列以下.NET代码

时间:2017-06-08 08:38:20

标签: php cryptography passwords sha512 pbkdf2

我真的不想转储一些代码并期待答案,但这是一个非常冗长的函数,它会记录密码,以便稍后将其与数据库存储的值进行比较。

我见过帖子,人们浪费时间尝试使用PHP中的md5()函数重新创建他们可以实现的功能。

出于这个原因,我想知道具有任何加密知识的人是否知道PHP相当于在PHP中实现以下效果:

    internal static string GenerateEncryptedPassword(string password, string salt, int iterationCount)
    {
        byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
        byte[] saltBytes = Encoding.UTF8.GetBytes(salt);
        byte[] iterationCountBytes = BitConverter.GetBytes(iterationCount);
        int derivedLength = passwordBytes.Length + saltBytes.Length;
        byte[] passwordSaltBytes = new byte[derivedLength];
        byte[] pbkdf2Bytes;
        string encryptedString;

        for (int i = 0; i < passwordBytes.Length; i++)
        {
            passwordSaltBytes[i] = passwordBytes[i];
        }

        for (int i = 0; i < saltBytes.Length; i++)
        {
            passwordSaltBytes[passwordBytes.Length + i] = saltBytes[i];
        }

        using (Rfc2898DeriveBytes pbkdf2 = new Rfc2898DeriveBytes(password, passwordSaltBytes, iterationCount))
        {
            pbkdf2Bytes = pbkdf2.GetBytes(derivedLength + iterationCountBytes.Length);
        }

        using (SHA512 sha512 = new SHA512Managed())
        {
            byte[] hashBytes = sha512.ComputeHash(pbkdf2Bytes);
            byte[] hashSaltBytes = new byte[hashBytes.Length + saltBytes.Length];

            for (int i = 0; i < hashBytes.Length; i++)
            {
                hashSaltBytes[i] = hashBytes[i];
            }

            for (int i = 0; i < saltBytes.Length; i++)
            {
                hashSaltBytes[hashBytes.Length + i] = saltBytes[i];
            }

            encryptedString = Convert.ToBase64String(hashSaltBytes);
        }

        return encryptedString;
    }

如果它改变了什么,我使用Laravel ......

感谢您提供任何指导

我讨厌加密:D

$user = \App\User::all();
$salt = strtolower($user[2]->Salt);
$password = 'P@$$W0rd';
$dbPassword = $user[2]->Password;
$iterations = 10000;

echo openssl_pbkdf2($password, $salt, 44, $iterations, 'sha512');

2 个答案:

答案 0 :(得分:0)

阅读用于password_hash和password_verify的PHP手册。我建议使用BCrypt作为算法。

http://php.net/manual/en/function.password-hash.php

http://php.net/manual/en/function.password-verify.php

这一点都不难!祝好运! : - )

此外,SHA-512不是那么安全。请在此处阅读:SHA1 vs md5 vs SHA256: which to use for a PHP login?

答案 1 :(得分:0)

我还没有使用PHP多年,所以不确定是否有新方法可以做,但是你可以使用OpenSSL生成SHA-512哈希:http://php.net/manual/en/function.openssl-digest.php

openssl_digest(pbkdf2Bytes, 'sha512');

为了生成盐,强烈建议使用安全(不可预测)的randoms。对于PHP,请参阅:PHP random string generator

修改 您还可以使用OpenSSL直接生成pbkfd2: http://php.net/manual/en/function.openssl-pbkdf2.php

请注意功能签名末尾的可选参数,您可以在其中定义摘要算法。

openssl_pbkdf2(password, saltBytes, keyLength, iterationCount, 'sha512')