在普通的PHP安装中,最简单的双向加密方式是什么?
我需要能够使用一个字符串密钥对数据进行加密,并在另一端使用相同的密钥来解密。
虽然安全性不是很大的问题,但代码的可移植性很重要,因此我希望能尽可能地保持简单。目前,我正在使用RC4实现,但如果我能找到本地支持的东西,我认为我可以节省很多不必要的代码。
在普通的PHP安装中,最简单的双向加密方式是什么?
我需要能够使用一个字符串密钥对数据进行加密,并在另一端使用相同的密钥来解密。
虽然安全性不是很大的问题,但代码的可移植性很重要,因此我希望能尽可能地保持简单。目前,我正在使用RC4实现,但如果我能找到本地支持的东西,我认为我可以节省很多不必要的代码。
openssl_encrypt()
和openssl_decrypt()
,一旦您对如何加密信息做出了一些决策。请参考openssl_get_cipher_methods()
以获取系统支持的方法列表。最好的选择是CTR模式下的AES:
aes-128-ctr
aes-192-ctr
aes-256-ctr
目前没有理由认为AES密钥大小是一个需要担心的重要问题(更大可能不更好,因为256位模式中存在糟糕的密钥调度)。
注意:我们没有使用mcrypt
,因为它已经被废弃并且存在未修补的漏洞可能会影响安全。因此,我鼓励其他PHP开发者也避免使用它。
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);
$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);
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);
SaferCrypto
库,或者使用同样的概念进行自己的实现,我强烈建议在执行前先向您所居住的密码学专家咨询,以获取第二意见。他们能够告诉您我可能没有意识到的错误。编辑:
你应该真正使用openssl_encrypt()和openssl_decrypt()。
正如Scott所说,Mcrypt不是一个好的选择,因为它自2007年以来就没有更新过。
甚至有一个RFC要从PHP中删除Mcrypt - https://wiki.php.net/rfc/mcrypt-viking-funeral
mcrypt_encrypt()
和 mcrypt_decrypt()
。非常简单明了,而且使用经过验证的加密包。
编辑
在此答案发布5年4个月之后,mcrypt
扩展现在正在逐渐被弃用并将从PHP中移除。使用openssl_encrypt()进行加密,这个函数提供了一种安全且简便的加密数据的方式。
在下面的脚本中,我们使用AES128加密方法,但是您可以根据要加密的内容选择其他类型的加密方法。
<?php
$message_to_encrypt = "Yoroshikune";
$secret_key = "my-secret-key";
$method = "aes128";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
$encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);
echo $encrypted_message;
?>
这里是使用的变量的解释:
message_to_encrypt:您想要加密的数据 secret_key:它是您的加密“密码”。一定不要选择太容易的东西,并小心不要与其他人分享您的秘密密钥。 method:加密方法。这里我们选择了AES128。 iv_length和iv:准备使用字节进行加密。 encrypted_message:包括您的加密消息的变量。
使用openssl_decrypt()进行解密 现在,您已经加密了您的数据,可能需要解密它以便重复使用您最初包含在变量中的消息。为了做到这一点,我们将使用函数openssl_decrypt()。
<?php
$message_to_encrypt = "Yoroshikune";
$secret_key = "my-secret-key";
$method = "aes128";
$iv_length = openssl_cipher_iv_length($method);
$iv = openssl_random_pseudo_bytes($iv_length);
$encrypted_message = openssl_encrypt($message_to_encrypt, $method, $secret_key, 0, $iv);
$decrypted_message = openssl_decrypt($encrypted_message, $method, $secret_key, 0, $iv);
echo $decrypted_message;
?>
由openssl_decrypt()提出的解密方法与openssl_encrypt()类似。
唯一的区别是,您需要将已加密的消息作为openssl_decrypt()的第一个参数,而不是添加$message_to_encrypt。
注意:秘密密钥和iv需要保存以便解密。
$iv
的值?我已经尝试过显示它并将其保存到文件,但是显示出来的内容无法读取,保存的文本看起来有点像base64编码之类的东西。我猜在脚本中保存这个值比明文密码更安全。 - StevePHP 7.2 已完全放弃了 Mcrypt
,现在的加密基于可维护的 Libsodium
库。
你的所有加密需求可以通过 Libsodium
库基本解决。
// On Alice's computer:
$msg = 'This comes from Alice.';
$signed_msg = sodium_crypto_sign($msg, $secret_sign_key);
// On Bob's computer:
$original_msg = sodium_crypto_sign_open($signed_msg, $alice_sign_publickey);
if ($original_msg === false) {
throw new Exception('Invalid signature');
} else {
echo $original_msg; // Displays "This comes from Alice."
}
Libsodium文档:https://github.com/paragonie/pecl-libsodium-doc
此链接提供了Libsodium文档,是一款现代且易于使用的加密库。它提供了密码学基本操作和高级功能,以保护网络通信、本地存储和身份验证等方面的数据安全。crypto_sign
API不会加密消息 - 这将需要使用crypto_aead_*_encrypt
函数之一。 - Roger Dueck重要提示:本答案仅适用于PHP 5,在PHP 7中请使用内置加密函数。
这里提供一个简单但足够安全的实现:
Sodium::crypto_secretbox()
和Sodium::crypto_secretbox_open()
是安全而且高效的方法。 - Scott Arciszewski