tec*_*hno 4 php encryption mcrypt
我正在使用以下代码使用 mcrypt 执行加密
<?PHP
define('SECURE_KEY','Somekey');
function encrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return mcrypt_encrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv);
}
function decrypt($value){
$iv_size = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_ECB);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);
return trim(mcrypt_decrypt(MCRYPT_RIJNDAEL_256, SECURE_KEY, $value, MCRYPT_MODE_ECB, $iv));
}
$temp=encrypt("teststring");
printf($temp);
?>
Run Code Online (Sandbox Code Playgroud)
较新版本的 php 贬值了 mcrypt,我正在寻找使用相同密钥并产生相同结果的相同替代品,这样我就不需要更改客户端代码。
我是 RFC 的作者,该 RFC旨在弃用并从 PHP 中删除 mcrypt。
您绝对应该做的就是迁移数据以使用新的 Sodium 扩展。了解如何在 PHP 中开始使用 libsodium。代码示例可以安全使用。
<?php
/**
* Wrap crypto_aead_*_encrypt() in a drop-dead-simple encryption interface
*
* @link https://paragonie.com/b/kIqqEWlp3VUOpRD7
* @param string $message
* @param string $key
* @return string
*/
function simpleEncrypt($message, $key)
{
$nonce = random_bytes(24); // NONCE = Number to be used ONCE, for each message
$encrypted = sodium_crypto_aead_xchacha20poly1305_ietf_encrypt(
$message,
$nonce,
$nonce,
$key
);
return $nonce . $encrypted;
}
/**
* Wrap crypto_aead_*_decrypt() in a drop-dead-simple decryption interface
*
* @link https://paragonie.com/b/kIqqEWlp3VUOpRD7
* @param string $message - Encrypted message
* @param string $key - Encryption key
* @return string
* @throws Exception
*/
function simpleDecrypt($message, $key)
{
$nonce = mb_substr($message, 0, 24, '8bit');
$ciphertext = mb_substr($message, 24, null, '8bit');
$plaintext = sodium_crypto_aead_xchacha20poly1305_ietf_decrypt(
$ciphertext,
$nonce,
$nonce,
$key
);
if (!is_string($plaintext)) {
throw new Exception('Invalid message');
}
return $plaintext;
}
$secretKey = random_bytes(32);
$message = 'Test message';
/* Encrypt the message: */
$ciphertext = simpleEncrypt($message, $secretKey);
/* Decrypt the message: */
try {
$decrypted = simpleDecrypt($ciphertext, $secretKey);
var_dump(hash_equals($decrypted, $message));
/* bool(true) */
} catch (Exception $ex) {
/* Someone is up to no good */
exit(255);
}
Run Code Online (Sandbox Code Playgroud)
如果您需要在 PHP 7.1 及更早版本和 PHP 7.2 及更高版本之间进行“过渡”步骤,mcrypt_compat是由 phpseclib 开发人员创建的一个 polyfill 库,用于促进 mcrypt 和非废弃软件库(OpenSSL、Sodium)之间的迁移。
仅将其用于迁移。不要依赖它来“正常工作”并保证安全。