2016-07-01 59 views
0

我的数据库将用户的登录密码存储在MD5中,因此当他们登录时,将其转换为MD5的密码与数据库中的MD5密码进行比较。如何在需要实际密码文本时存储密码

我正在实现应用程序可以使用IMAP连接到他们的电子邮件帐户的功能。因此,我需要将用户的电子邮件帐户密码存储在数据库中,但据我所知,我无法使用MD5,因为我需要以纯文本形式输入密码,以便通过IMAP连接进行连接。

什么是将密码安全地存储在数据库中的解决方案,但是能够检索并将其转换为脚本中的纯文本?

回答

0

首先,MD5不是存储密码的安全方式。看看password_hash功能和bcrypt为更现代和安全的解决方案。另请参阅:How do you use bcrypt for hashing passwords in PHP?

至于IMAP密码,你做不是需要散列,因为那些是“单向”。你需要一个加密算法。

更好的选择之一是使用openssl_encrypt()和存储在服务器上的安全密钥。这是Laravel采取的方法。

看一看此作为一个例子:https://github.com/laravel/framework/blob/5.2/src/Illuminate/Encryption/Encrypter.php#L62

/** 
* Encrypt the given value. 
* 
* @param string $value 
* @return string 
* 
* @throws \Illuminate\Contracts\Encryption\EncryptException 
*/ 
public function encrypt($value) 
{ 
    $iv = random_bytes($this->getIvSize()); 
    $value = \openssl_encrypt(serialize($value), $this->cipher, $this->key, 0, $iv); 
    if ($value === false) { 
     throw new EncryptException('Could not encrypt the data.'); 
    } 
    // Once we have the encrypted value we will go ahead base64_encode the input 
    // vector and create the MAC for the encrypted value so we can verify its 
    // authenticity. Then, we'll JSON encode the data in a "payload" array. 
    $mac = $this->hash($iv = base64_encode($iv), $value); 
    $json = json_encode(compact('iv', 'value', 'mac')); 
    if (! is_string($json)) { 
     throw new EncryptException('Could not encrypt the data.'); 
    } 
    return base64_encode($json); 
} 
/** 
* Decrypt the given value. 
* 
* @param string $payload 
* @return string 
* 
* @throws \Illuminate\Contracts\Encryption\DecryptException 
*/ 
public function decrypt($payload) 
{ 
    $payload = $this->getJsonPayload($payload); 
    $iv = base64_decode($payload['iv']); 
    $decrypted = \openssl_decrypt($payload['value'], $this->cipher, $this->key, 0, $iv); 
    if ($decrypted === false) { 
     throw new DecryptException('Could not decrypt the data.'); 
    } 
    return unserialize($decrypted); 
} 
/** 
* Get the IV size for the cipher. 
* 
* @return int 
*/ 
protected function getIvSize() 
{ 
    return 16; 
} 

显然,Laravel代码依赖于Laravel的其它部分,但作为一个例子,这是足够的。获得加密值后,可以将其存储在数据库中。

记住安全性与最薄弱的环节一样强大 - 因此请确保您的数据库凭据是安全的,并且您的数据库用户拥有最低数量的权限,以便您的应用程序正常工作。

+1

非常好,谢谢你的信息 – dlofrodloh

+0

为什么在解密过程中没有检查到加密的时候为它创建一个mac? – zaph

+0

@ zaph,这是一个很好的问题。不知道泰勒的过程是什么过程是这样的。 –