使用php7使用salt加密/解密字符串

时间:2017-12-28 01:14:47

标签: php encryption php-7 salt password-hash

我有一个字符串,我想将此字符串安全地存储在数据库中。

因此,我想到的是使用用户密码作为加密密钥加密此字符串。

当用户需要使用此字符串时,我们使用该密钥对其进行解密。

是否有一些算法可以帮助将这些字符串安全地存储在数据库中,从而阻止任何人访问它甚至团队?

1 个答案:

答案 0 :(得分:3)

您想使用某种类型的共享密钥加密算法,如AES。 openssl和mcrypt都应该支持这一点。我建议使用openssl,因为mcrypt是EOL。

以下示例直接来自php.net。您可能不需要hmac,因为您想要检索原始数据。

<?php
//$key previously generated safely, ie: openssl_random_pseudo_bytes
$plaintext = "message to be encrypted";
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = openssl_random_pseudo_bytes($ivlen);
$ciphertext_raw = openssl_encrypt($plaintext, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
//$hmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
$ciphertext = base64_encode( $iv./*$hmac.*/$ciphertext_raw );

//decrypt later....
$c = base64_decode($ciphertext);
$ivlen = openssl_cipher_iv_length($cipher="AES-128-CBC");
$iv = substr($c, 0, $ivlen);
//$hmac = substr($c, $ivlen, $sha2len=32);
$ciphertext_raw = substr($c, $ivlen/*+$sha2len*/);
$original_plaintext = openssl_decrypt($ciphertext_raw, $cipher, $key, $options=OPENSSL_RAW_DATA, $iv);
/*
$calcmac = hash_hmac('sha256', $ciphertext_raw, $key, $as_binary=true);
if (hash_equals($hmac, $calcmac))//PHP 5.6+ timing attack safe comparison
{
    echo $original_plaintext."\n";
}
*/