gpt4 book ai didi

php - 试图让 openssl_encrypt 工作的问题

转载 作者:可可西里 更新时间:2023-11-01 13:47:26 25 4
gpt4 key购买 nike

我正在编写一个类来处理加密数据,本质上它将用于加密要存储在数据库中的数据,然后在检索时再次对其进行解密。

这是我写的:

    class dataEncrypt {

private $encryptString;
private $decryptString;
private $encryptionMethod;
private $key;

public function __construct() {

/* IMPORTANT - DONT CHANGE OR DATA WILL DAMAGE */
$this->key = sha1('StringToHash');

// Set the encryption type
$this->encryptionMethod = "AES-256-CBC";

}

// Generate the IV key
private function generateIV() {

$ivSize = mcrypt_get_iv_size(MCRYPT_RIJNDAEL_256, MCRYPT_MODE_CBC);
return mcrypt_create_iv($ivSize, MCRYPT_RAND);
}

// Retrieve the key
private function retrieveKey() {

return $key;
}

// Encrypt a string
public function encryptString($string) {

// Return the encrypted value for storage
return openssl_encrypt($string, $this->encryptionMethod, $this->retrieveKey(), 0, $this->generateIV());
}

// Decrypt a string
public function decryptString($data) {

// return the decrypted data
return openssl_decrypt($data, $this->encryptionMethod, $this->retrieveKey(), 0, $this->generateIV());

return false;

}

}

我试图在存储之前加密一个字符串,但我收到以下 PHP 警告:

Warning: openssl_encrypt(): IV passed is 32 bytes long which is longer than the 16 expected by selected cipher, truncating in /var/www/blahblah... on line xxx

我在谷歌上搜索过这个,我在谷歌上搜索过 IV 函数,我都找不到 sweetheat。欢迎提出任何建议。

谢谢

最佳答案

我能够通过将 MCRYPT_CAST_256 而不是 MCRYPT_RIJNDAEL_256 传递给 mcrypt_get_iv_size 来让它工作

加密:

$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = mcrypt_create_iv($iv_size, MCRYPT_RAND);

$encrypted = openssl_encrypt($string, "AES-256-CBC", $key, 0, $iv);
$encrypted = $iv.$encrypted;

解密

$iv_size = mcrypt_get_iv_size(MCRYPT_CAST_256, MCRYPT_MODE_CBC);
$iv = substr($string, 0, $iv_size);

$decrypted = openssl_decrypt(substr($string, $iv_size), "AES-256-CBC", $key, 0, $iv);

关于php - 试图让 openssl_encrypt 工作的问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17792492/

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