双向加密:我需要存储可以检索的密码 [英] Two-way encryption: I need to store passwords that can be retrieved

查看:135
本文介绍了双向加密:我需要存储可以检索的密码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在创建一个将存储密码的应用程序,用户可以检索和查看密码。密码是硬件设备,所以检查散列是不成问题的。

I am creating an application that will store passwords, which the user can retrieve and see. The passwords are for a hardware device, so checking against hashes are out of the question.

我需要知道的是:


  1. 如何在PHP中加密和解密密码?

  1. How do I encrypt and decrypt a password in PHP?

什么是最安全的算法加密密码?

What is the safest algorithm to encrypt the passwords with?

我在哪里存储私钥?

存储私钥,是否需要用户在需要密码解密时才输入私钥是一个好主意? (此应用程序的用户可以信任)

Instead of storing the private key, is it a good idea to require users to enter the private key any time they need a password decrypted? (Users of this application can be trusted)

密码被盗用和解密的方式如何?我需要注意什么?

In what ways can the password be stolen and decrypted? What do I need to be aware of?


推荐答案

像其他人一样使用 mcrypt 但是还有更多的注意事项...

Personally, I would use mcrypt like others posted. But there is much more to note...


  1. 如何在PHP中加密和解密密码?

  1. How do I encrypt and decrypt a password in PHP?

请参阅下面的强化类,为您处理一切:

See below for a strong class that takes care of everything for you:

什么是最安全的加密算法密码与?

What is the safest algorithm to encrypt the passwords with?

最安全?任何一位。如果要加密,最安全的方法是防范信息泄露漏洞(XSS,远程包含等)。如果它出来,攻击者最终可能会破解加密(没有加密是100%不可逆的没有密钥 - As @NullUserException指出这不完全正确。有一些加密方案是不可能破解的,例如 OneTimePad )。

safest? any of them. The safest method if you're going to encrypt is to protect against information disclosure vulnerabilities (XSS, remote inclusion, etc). If it gets out, the attacker can eventually crack the encryption (no encryption is 100% un-reversible without the key - As @NullUserException points out this is not entirely true. There are some encryption schemes that are impossible to crack such as OneTimePad).

我在哪里存储私人密钥?

Where do I store the private key?

我要做的是使用3个键。一个是用户提供的,一个是特定于应用程序,另一个是用户特定的(如盐)。应用程序特定的密钥可以存储在任何地方(在web根目录下的配置文件,环境变量等中)。用户特定的用户将被存储在加密密码旁边的数据库的列中。提供的用户将不被存储。那么你可以这样做:

What I would do is use 3 keys. One is user supplied, one is application specific and the other is user specific (like a salt). The application specific key can be stored anywhere (in a config file outside of the web-root, in an environmental variable, etc). The user specific one would be stored in a column in the db next to the encrypted password. The user supplied one would not be stored. Then, you'd do something like this:

$key = $userKey . $serverKey . $userSuppliedKey;

这里的好处是,任何2个密钥都可以在没有数据泄露的情况下受到威胁。如果有一个SQL注入攻击,他们可以获得 $ userKey ,而不是其他2.如果有一个本地服务器漏洞利用,他们可以得到 $ userKey $ serverKey ,而不是第三个 $ userSuppliedKey 。如果他们用扳手打败用户,他们可以获得 $ userSuppliedKey ,而不是其他2(但是再次,如果用户用扳手殴打,你反正太晚了)

The benefit there, is that any 2 of the keys can be compromised without the data being compromised. If there's a SQL Injection attack, they can get the $userKey, but not the other 2. If there's a local server exploit, they can get $userKey and $serverKey, but not the third $userSuppliedKey. If they go beat the user with a wrench, they can get the $userSuppliedKey, but not the other 2 (but then again, if the user is beaten with a wrench, you're too late anyway).

代替存储私钥,是否需要用户在需要密码解密时输入私钥是个好主意? (此应用程序的用户可以信任)

Instead of storing the private key, is it a good idea to require users to enter the private key any time they need a password decrypted? (Users of this application can be trusted)

绝对。事实上,这是我唯一的办法。否则,您需要以耐用存储格式(共享内存,如APC或memcached或会话文件)存储未加密的版本。这是暴露自己的额外妥协。不要将未加密版本的密码存储在除本地变量之外的任何内容中。

Absolutely. In fact, that's the only way I would do it. Otherwise you'd need to store an unencrypted version in a durable storage format (shared memory such as APC or memcached, or in a session file). That's exposing yourself to additional compromises. Never store the unencrypted version of the password in anything except a local variable.

密码被盗取和解密的方式如何?我需要注意什么?

In what ways can the password be stolen and decrypted? What do I need to be aware of?

您的系统的任何形式的妥协将让他们查看加密的数据。如果他们可以注入代码或获取到您的文件系统,他们可以查看解密的数据(因为他们可以编辑解密数据的文件)。任何形式的Replay或MITM攻击也将使他们完全访问所涉及的密钥。嗅探原始HTTP流量也会给他们提供密钥。

Any form of compromise of your systems will let them view encrypted data. If they can inject code or get to your filesystem, they can view decrypted data (since they can edit the files that decrypt the data). Any form of Replay or MITM attack will also give them full access to the keys involved. Sniffing the raw HTTP traffic will also give them the keys.

对所有流量使用SSL。并确保服务器上没有任何漏洞(CSRF,XSS,SQL注入,特权升级,远程执行代码等)。

Use SSL for all traffic. And make sure nothing on the server has any kind of vulnerabilities (CSRF, XSS, SQL Injection, Privilege Escalation, Remote Code Execution, etc).

编辑:这是一个强大的加密方法的PHP类实现:

Here's a PHP class implementation of a strong encryption method:

/**
 * A class to handle secure encryption and decryption of arbitrary data
 *
 * Note that this is not just straight encryption.  It also has a few other
 *  features in it to make the encrypted data far more secure.  Note that any
 *  other implementations used to decrypt data will have to do the same exact
 *  operations.  
 *
 * Security Benefits:
 *
 * - Uses Key stretching
 * - Hides the Initialization Vector
 * - Does HMAC verification of source data
 *
 */
class Encryption {

    /**
     * @var string $cipher The mcrypt cipher to use for this instance
     */
    protected $cipher = '';

    /**
     * @var int $mode The mcrypt cipher mode to use
     */
    protected $mode = '';

    /**
     * @var int $rounds The number of rounds to feed into PBKDF2 for key generation
     */
    protected $rounds = 100;

    /**
     * Constructor!
     *
     * @param string $cipher The MCRYPT_* cypher to use for this instance
     * @param int    $mode   The MCRYPT_MODE_* mode to use for this instance
     * @param int    $rounds The number of PBKDF2 rounds to do on the key
     */
    public function __construct($cipher, $mode, $rounds = 100) {
        $this->cipher = $cipher;
        $this->mode = $mode;
        $this->rounds = (int) $rounds;
    }

    /**
     * Decrypt the data with the provided key
     *
     * @param string $data The encrypted datat to decrypt
     * @param string $key  The key to use for decryption
     * 
     * @returns string|false The returned string if decryption is successful
     *                           false if it is not
     */
    public function decrypt($data, $key) {
        $salt = substr($data, 0, 128);
        $enc = substr($data, 128, -64);
        $mac = substr($data, -64);

        list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key);

        if (!hash_equals(hash_hmac('sha512', $enc, $macKey, true), $mac)) {
             return false;
        }

        $dec = mcrypt_decrypt($this->cipher, $cipherKey, $enc, $this->mode, $iv);

        $data = $this->unpad($dec);

        return $data;
    }

    /**
     * Encrypt the supplied data using the supplied key
     * 
     * @param string $data The data to encrypt
     * @param string $key  The key to encrypt with
     *
     * @returns string The encrypted data
     */
    public function encrypt($data, $key) {
        $salt = mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);
        list ($cipherKey, $macKey, $iv) = $this->getKeys($salt, $key);

        $data = $this->pad($data);

        $enc = mcrypt_encrypt($this->cipher, $cipherKey, $data, $this->mode, $iv);

        $mac = hash_hmac('sha512', $enc, $macKey, true);
        return $salt . $enc . $mac;
    }

    /**
     * Generates a set of keys given a random salt and a master key
     *
     * @param string $salt A random string to change the keys each encryption
     * @param string $key  The supplied key to encrypt with
     *
     * @returns array An array of keys (a cipher key, a mac key, and a IV)
     */
    protected function getKeys($salt, $key) {
        $ivSize = mcrypt_get_iv_size($this->cipher, $this->mode);
        $keySize = mcrypt_get_key_size($this->cipher, $this->mode);
        $length = 2 * $keySize + $ivSize;

        $key = $this->pbkdf2('sha512', $key, $salt, $this->rounds, $length);

        $cipherKey = substr($key, 0, $keySize);
        $macKey = substr($key, $keySize, $keySize);
        $iv = substr($key, 2 * $keySize);
        return array($cipherKey, $macKey, $iv);
    }

    /**
     * Stretch the key using the PBKDF2 algorithm
     *
     * @see http://en.wikipedia.org/wiki/PBKDF2
     *
     * @param string $algo   The algorithm to use
     * @param string $key    The key to stretch
     * @param string $salt   A random salt
     * @param int    $rounds The number of rounds to derive
     * @param int    $length The length of the output key
     *
     * @returns string The derived key.
     */
    protected function pbkdf2($algo, $key, $salt, $rounds, $length) {
        $size   = strlen(hash($algo, '', true));
        $len    = ceil($length / $size);
        $result = '';
        for ($i = 1; $i <= $len; $i++) {
            $tmp = hash_hmac($algo, $salt . pack('N', $i), $key, true);
            $res = $tmp;
            for ($j = 1; $j < $rounds; $j++) {
                 $tmp  = hash_hmac($algo, $tmp, $key, true);
                 $res ^= $tmp;
            }
            $result .= $res;
        }
        return substr($result, 0, $length);
    }

    protected function pad($data) {
        $length = mcrypt_get_block_size($this->cipher, $this->mode);
        $padAmount = $length - strlen($data) % $length;
        if ($padAmount == 0) {
            $padAmount = $length;
        }
        return $data . str_repeat(chr($padAmount), $padAmount);
    }

    protected function unpad($data) {
        $length = mcrypt_get_block_size($this->cipher, $this->mode);
        $last = ord($data[strlen($data) - 1]);
        if ($last > $length) return false;
        if (substr($data, -1 * $last) !== str_repeat(chr($last), $last)) {
            return false;
        }
        return substr($data, 0, -1 * $last);
    }
}

请注意,我正在使用PHP中添加的函数5.6: hash_equals 。如果你低于5.6,你可以使用这个替代功能实现一个计时安全比较功能使用双HMAC验证

Note that I'm using a function added in PHP 5.6: hash_equals. If you're on lower than 5.6, you can use this substitute function which implements a timing-safe comparison function using double HMAC verification:

function hash_equals($a, $b) {
    $key = mcrypt_create_iv(128, MCRYPT_DEV_URANDOM);
    return hash_hmac('sha512', $a, $key) === hash_hmac('sha512', $b, $key);
}

用法:

$e = new Encryption(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$encryptedData = $e->encrypt($data, $key);

然后,解密:

$e2 = new Encryption(MCRYPT_BLOWFISH, MCRYPT_MODE_CBC);
$data = $e2->decrypt($encryptedData, $key);

请注意,我使用 $ e2 第二时间显示不同的实例仍然可以正确解密数据。

Note that I used $e2 the second time to show you different instances will still properly decrypt the data.

现在,它是如何工作的/为什么使用它超过另一种解决方案:

Now, how does it work/why use it over another solution:


  1. Keys


  • 键不直接使用。相反,密钥被标准的PBKDF2推导拉伸。

  • The keys are not directly used. Instead, the key is stretched by a standard PBKDF2 derivation.

用于加密的密钥对于每个加密的文本块是唯一的。所提供的密钥因此成为主密钥。

The key used for encryption is unique for every encrypted block of text. The supplied key therefore becomes a "master key". This class therefore provides key rotation for cipher and auth keys.

重要注意 $ rounds 参数配置为具有足够强度的真随机密钥(至少128位密码安全随机)。如果要使用密码或非随机密钥(或随机随机的128位随机密钥),则必须增加此参数。我建议至少10000个密码(你买得越多越好,但会增加到运行时)...

IMPORTANT NOTE, the $rounds parameter is configured for true random keys of sufficient strength (128 bits of Cryptographically Secure random at a minimum). If you are going to use a password, or non-random key (or less random then 128 bits of CS random), you must increase this parameter. I would suggest a minimum of 10000 for passwords (the more you can afford, the better, but it will add to the runtime)...

数据完整性


  • 更新版本使用ENCRYPT-THEN-MAC,这是一个更好的方法确保加密数据的真实性。

加密:


  • 它使用mcrypt来实际执行加密。我建议使用 MCRYPT_BLOWFISH MCRYPT_RIJNDAEL_128 cyphers和 MCRYPT_MODE_CBC 为模式。它足够强大,仍然相当快(在我的机器上加密和解密周期大约需要1/2秒)。

  • It uses mcrypt to actually perform the encryption. I would suggest using either MCRYPT_BLOWFISH or MCRYPT_RIJNDAEL_128 cyphers and MCRYPT_MODE_CBC for the mode. It's strong enough, and still fairly fast (an encryption and decryption cycle takes about 1/2 second on my machine).

现在,关于第一个列表中的第3点,你是一个这样的功能:

Now, as to point 3 from the first list, what that would give you is a function like this:

function makeKey($userKey, $serverKey, $userSuppliedKey) {
    $key = hash_hmac('sha512', $userKey, $serverKey);
    $key = hash_hmac('sha512', $key, $userSuppliedKey);
    return $key;
}

您可以在 makeKey() / code>函数,但由于以后会被拉伸,所以没有太大的意义。

You could stretch it in the makeKey() function, but since it's going to be stretched later, there's not really a huge point to doing so.

就存储大小而言取决于纯文本。 Blowfish使用8字节块大小,因此您将具有:

As far as the storage size, it depends on the plain text. Blowfish uses a 8 byte block size, so you'll have:


  • 盐的16个字节

  • 64字节hmac

  • 数据长度

  • 填充数据长度%8 == 0

  • 16 bytes for the salt
  • 64 bytes for the hmac
  • data length
  • Padding so that data length % 8 == 0

所以对于一个16字符的数据源,将有16个字符的数据被加密。这意味着实际的加密数据大小由于填充而是16字节。然后添加盐的16个字节和hmac的64个字节,总存储的大小是96字节。所以最多有80个字符的开销,最糟糕的是一个87个字符的开销...

So for a 16 character data source, there will be 16 characters of data to be encrypted. So that means the actual encrypted data size is 16 bytes due to padding. Then add the 16 bytes for the salt and 64 bytes for the hmac and the total stored size is 96 bytes. So there's at best a 80 character overhead, and at worst a 87 character overhead...

我希望有帮助...

注意: 12/11/12:我刚刚使用更好的加密方法更新了这个类,使用更好的派生密钥,并修复了MAC生成...

Note: 12/11/12: I just updated this class with a MUCH better encryption method, using better derived keys, and fixing the MAC generation...

这篇关于双向加密:我需要存储可以检索的密码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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