重要提示:除非您有一个非常特定的用例do not encrypt passwords,否则请改用密码哈希算法。当有人说他们在服务器端应用程序中加密他们的密码时,他们要么不知情,要么在描述危险的系统设计。 Safely storing passwords 是与加密完全不同的问题。
了解情况。设计安全系统。
PHP 中的可移植数据加密
如果您使用PHP 5.4 or newer 并且不想自己编写加密模块,我建议您使用an existing library that provides authenticated encryption。我链接的库仅依赖于 PHP 提供的内容,并且正在接受少数安全研究人员的定期审查。 (包括我自己。)
如果您的可移植性目标不妨碍需要 PECL 扩展,则强烈推荐使用 libsodium,而不是您或我可以用 PHP 编写的任何内容。
更新 (2016-06-12):您现在可以使用 sodium_compat 并使用相同的加密 libsodium 提供,而无需安装 PECL 扩展。
如果您想尝试密码学工程,请继续阅读。
首先,你应该花时间学习the dangers of unauthenticated encryption和the Cryptographic Doom Principle。
- 加密数据仍可能被恶意用户篡改。
- 对加密数据进行身份验证可防止篡改。
- 对未加密数据进行身份验证并不能防止篡改。
加解密
PHP 中的加密实际上很简单(一旦您决定如何加密您的信息,我们将使用openssl_encrypt() 和openssl_decrypt()。请咨询openssl_get_cipher_methods() 以获取系统支持的方法列表. 最好的选择是AES in CTR mode:
aes-128-ctr
aes-192-ctr
aes-256-ctr
目前没有理由相信AES key size 是一个需要担心的重大问题(由于 256 位模式下的键调度错误,可能不是越大越好)。
注意:我们没有使用mcrypt,因为它是abandonware,并且有可能影响安全的unpatched bugs。由于这些原因,我鼓励其他 PHP 开发人员也避免使用它。
使用 OpenSSL 的简单加密/解密包装器
class UnsafeCrypto
{
const METHOD = 'aes-256-ctr';
/**
* Encrypts (but does not authenticate) a message
*
* @param string $message - plaintext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encode - set to TRUE to return a base64-encoded
* @return string (raw binary)
*/
public static function encrypt($message, $key, $encode = false)
{
$nonceSize = openssl_cipher_iv_length(self::METHOD);
$nonce = openssl_random_pseudo_bytes($nonceSize);
$ciphertext = openssl_encrypt(
$message,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$nonce
);
// Now let's pack the IV and the ciphertext together
// Naively, we can just concatenate
if ($encode) {
return base64_encode($nonce.$ciphertext);
}
return $nonce.$ciphertext;
}
/**
* Decrypts (but does not verify) a message
*
* @param string $message - ciphertext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encoded - are we expecting an encoded string?
* @return string
*/
public static function decrypt($message, $key, $encoded = false)
{
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
throw new Exception('Encryption failure');
}
}
$nonceSize = openssl_cipher_iv_length(self::METHOD);
$nonce = mb_substr($message, 0, $nonceSize, '8bit');
$ciphertext = mb_substr($message, $nonceSize, null, '8bit');
$plaintext = openssl_decrypt(
$ciphertext,
self::METHOD,
$key,
OPENSSL_RAW_DATA,
$nonce
);
return $plaintext;
}
}
使用示例
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = UnsafeCrypto::encrypt($message, $key);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key);
var_dump($encrypted, $decrypted);
演示:https://3v4l.org/jl7qR
上述简单的加密库仍然不能安全使用。我们需要authenticate ciphertexts and verify them before we decrypt。
注意:默认情况下,UnsafeCrypto::encrypt() 将返回原始二进制字符串。如果您需要以二进制安全格式(base64 编码)存储它,可以这样调用它:
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = UnsafeCrypto::encrypt($message, $key, true);
$decrypted = UnsafeCrypto::decrypt($encrypted, $key, true);
var_dump($encrypted, $decrypted);
演示:http://3v4l.org/f5K93
简单的身份验证包装器
class SaferCrypto extends UnsafeCrypto
{
const HASH_ALGO = 'sha256';
/**
* Encrypts then MACs a message
*
* @param string $message - plaintext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encode - set to TRUE to return a base64-encoded string
* @return string (raw binary)
*/
public static function encrypt($message, $key, $encode = false)
{
list($encKey, $authKey) = self::splitKeys($key);
// Pass to UnsafeCrypto::encrypt
$ciphertext = parent::encrypt($message, $encKey);
// Calculate a MAC of the IV and ciphertext
$mac = hash_hmac(self::HASH_ALGO, $ciphertext, $authKey, true);
if ($encode) {
return base64_encode($mac.$ciphertext);
}
// Prepend MAC to the ciphertext and return to caller
return $mac.$ciphertext;
}
/**
* Decrypts a message (after verifying integrity)
*
* @param string $message - ciphertext message
* @param string $key - encryption key (raw binary expected)
* @param boolean $encoded - are we expecting an encoded string?
* @return string (raw binary)
*/
public static function decrypt($message, $key, $encoded = false)
{
list($encKey, $authKey) = self::splitKeys($key);
if ($encoded) {
$message = base64_decode($message, true);
if ($message === false) {
throw new Exception('Encryption failure');
}
}
// Hash Size -- in case HASH_ALGO is changed
$hs = mb_strlen(hash(self::HASH_ALGO, '', true), '8bit');
$mac = mb_substr($message, 0, $hs, '8bit');
$ciphertext = mb_substr($message, $hs, null, '8bit');
$calculated = hash_hmac(
self::HASH_ALGO,
$ciphertext,
$authKey,
true
);
if (!self::hashEquals($mac, $calculated)) {
throw new Exception('Encryption failure');
}
// Pass to UnsafeCrypto::decrypt
$plaintext = parent::decrypt($ciphertext, $encKey);
return $plaintext;
}
/**
* Splits a key into two separate keys; one for encryption
* and the other for authenticaiton
*
* @param string $masterKey (raw binary)
* @return array (two raw binary strings)
*/
protected static function splitKeys($masterKey)
{
// You really want to implement HKDF here instead!
return [
hash_hmac(self::HASH_ALGO, 'ENCRYPTION', $masterKey, true),
hash_hmac(self::HASH_ALGO, 'AUTHENTICATION', $masterKey, true)
];
}
/**
* Compare two strings without leaking timing information
*
* @param string $a
* @param string $b
* @ref https://paragonie.com/b/WS1DLx6BnpsdaVQW
* @return boolean
*/
protected static function hashEquals($a, $b)
{
if (function_exists('hash_equals')) {
return hash_equals($a, $b);
}
$nonce = openssl_random_pseudo_bytes(32);
return hash_hmac(self::HASH_ALGO, $a, $nonce) === hash_hmac(self::HASH_ALGO, $b, $nonce);
}
}
使用示例
$message = 'Ready your ammunition; we attack at dawn.';
$key = hex2bin('000102030405060708090a0b0c0d0e0f101112131415161718191a1b1c1d1e1f');
$encrypted = SaferCrypto::encrypt($message, $key);
$decrypted = SaferCrypto::decrypt($encrypted, $key);
var_dump($encrypted, $decrypted);
演示:raw binary、base64-encoded
如果有人希望在生产环境中使用这个SaferCrypto 库,或者您自己实现相同的概念,我强烈建议您在这样做之前联系your resident cryptographers 以获得第二意见。他们会告诉你我可能没有意识到的错误。
使用a reputable cryptography library 会更好。