使用 PHP 加密和解密密码的最佳方法? [英] Best way to use PHP to encrypt and decrypt passwords?

查看:31
本文介绍了使用 PHP 加密和解密密码的最佳方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

可能的重复:
PHP 2 路加密:我需要存储可以找回的密码

我计划在我的网站上为我的用户存储外国帐户信息,又名 Rapidshare 用户名和密码等...我想确保信息安全,但我知道如果我散列他们的信息,我将无法检索它供以后使用.

I plan to store foreign account information for my users on my website, aka rapidshare username and passwords, etc... I want to keep information secure, but I know that if I hash their information, I can't retrieve it for later use.

Base64 是可解密的,所以直接使用它是没有意义的.我的想法是打乱用户并在它以这种方式进行 base64ed 之前和之后通过,即使在您解密之后,如果您尝试解密,您也会得到一些看起来很有趣的文本.是否有一个 php 函数接受值,这些值将对字符串进行唯一的加扰,并在稍后重新输入该值时对其进行解扰?

Base64 is decrypt-able so there's no point using that just plain off. My idea is to scramble the user and pass before and after it gets base64ed that way even after you decrypt it, you get some funny looking text if you try to decrypt. Is there a php function that accepts values that will make an unique scramble of a string and de-scramble it later when the value is reinputed?

有什么建议吗?

推荐答案

你不应该加密密码,而应该使用像 bcrypt 这样的算法来散列它们.这个答案解释了如何在 PHP 中正确实现密码散列. 不过,这里是您加密/解密的方法:

You should not encrypt passwords, instead you should hash them using an algorithm like bcrypt. This answer explains how to properly implement password hashing in PHP. Still, here is how you would encrypt/decrypt:

$key = 'password to (en/de)crypt';
$string = ' string to be encrypted '; // note the spaces

加密:

$iv = mcrypt_create_iv(
    mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC),
    MCRYPT_DEV_URANDOM
);

$encrypted = base64_encode(
    $iv .
    mcrypt_encrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        $string,
        MCRYPT_MODE_CBC,
        $iv
    )
);

解密:

$data = base64_decode($encrypted);
$iv = substr($data, 0, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC));

$decrypted = rtrim(
    mcrypt_decrypt(
        MCRYPT_RIJNDAEL_128,
        hash('sha256', $key, true),
        substr($data, mcrypt_get_iv_size(MCRYPT_RIJNDAEL_128, MCRYPT_MODE_CBC)),
        MCRYPT_MODE_CBC,
        $iv
    ),
    ""
);

<小时>

警告:以上示例对信息进行了加密,但并未对密文进行身份验证以防止篡改.您应该不要依赖未经身份验证的加密来获取安全,特别是因为所提供的代码容易受到填充预言机攻击.


Warning: The above example encrypts information, but it does not authenticate the ciphertext to prevent tampering. You should not rely on unauthenticated encryption for security, especially since the code as provided is vulnerable to padding oracle attacks.

另见:

此外,不要只使用密码"作为加密密钥.加密密钥是随机字符串.

Also, don't just use a "password" for an encryption key. Encryption keys are random strings.

演示在 3v4l.org:

echo 'Encrypted:' . "
";
var_dump($encrypted); // "m1DSXVlAKJnLm7k3WrVd51omGL/05JJrPluBonO9W+9ohkNuw8rWdJW6NeLNc688="

echo "
";

echo 'Decrypted:' . "
";
var_dump($decrypted); // " string to be encrypted "

这篇关于使用 PHP 加密和解密密码的最佳方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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