gpt4 book ai didi

php - MCRYPT 的等效加密 - 保留客户端代码

转载 作者:行者123 更新时间:2023-12-05 04:01:28 29 4
gpt4 key购买 nike

我正在使用以下代码使用 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);
?>

较新版本的 php 贬低了 mcrypt,我正在寻找使用相同 key 并产生相同结果的相同版本的替代品,因此我不需要更改客户端代码。

最佳答案

我是 RFC to deprecate then remove mcrypt from PHP 的作者.

您绝对应该做的是迁移您的数据以改用新的 Sodium 扩展程序。 Learn how to get started with libsodium in PHP .代码示例可以安全使用。

<?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);
}

如果您需要在 PHP 7.1 和更早版本以及 PHP 7.2 和更新版本之间执行“转换”步骤,mcrypt_compat是由 phpseclib 开发人员创建的 polyfill 库,用于促进 mcrypt 和非废弃软件库(OpenSSL、Sodium)之间的迁移。

仅用于迁移。不要依赖它来“正常工作”并确保安全。

关于php - MCRYPT 的等效加密 - 保留客户端代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55370485/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com