如何将 openssl_encrypt 上的 IV 转换为字符串?
How to convert IV on openssl_encrypt to string?
我有这个加密字符串的代码。
$textToEncrypt = "some text to encrypt";
$secretHash = "some-hash";
$encryptionMethod = "AES-256-CBC";
$ivlen1 = openssl_cipher_iv_length($encryptionMethod);
$iv1 = openssl_random_pseudo_bytes($ivlen1);
$encryptedMessage1 = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash, 0, $iv1);
而且我能够使用秘密哈希和 iv 对其进行加密和解密。我的问题是,iv 是按字节计算的。我如何将它转换为字符串,以便“解密器”知道它是什么并能够解密。
提前致谢。
函数“openssl_random_pseudo_bytes”生成一个伪随机字节串。您可以创建自己的方法来生成随机字符串以用作您的 IV。
但是,如果您特别想让这个二进制数据显示为不是随机垃圾的字符串,您可以通过“bin2hex”函数传递它。
echo $iv1 . "\n"; //outputs something like: "��I݂6B{�M [r"
$stored = bin2hex($iv1);
echo $stored . "\n"; //outputs something like: "8cbc49dd82361508427be5954d0d5b72"
这为您提供了一个可用的字符串,如果您需要原始二进制数据,您只需将该字符串通过函数“hex2bin”传回即可。
echo hex2bin($stored); //again something like: "��I݂6B{�M [r"
我有这个加密字符串的代码。
$textToEncrypt = "some text to encrypt";
$secretHash = "some-hash";
$encryptionMethod = "AES-256-CBC";
$ivlen1 = openssl_cipher_iv_length($encryptionMethod);
$iv1 = openssl_random_pseudo_bytes($ivlen1);
$encryptedMessage1 = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash, 0, $iv1);
而且我能够使用秘密哈希和 iv 对其进行加密和解密。我的问题是,iv 是按字节计算的。我如何将它转换为字符串,以便“解密器”知道它是什么并能够解密。
提前致谢。
函数“openssl_random_pseudo_bytes”生成一个伪随机字节串。您可以创建自己的方法来生成随机字符串以用作您的 IV。
但是,如果您特别想让这个二进制数据显示为不是随机垃圾的字符串,您可以通过“bin2hex”函数传递它。
echo $iv1 . "\n"; //outputs something like: "��I݂6B{�M [r"
$stored = bin2hex($iv1);
echo $stored . "\n"; //outputs something like: "8cbc49dd82361508427be5954d0d5b72"
这为您提供了一个可用的字符串,如果您需要原始二进制数据,您只需将该字符串通过函数“hex2bin”传回即可。
echo hex2bin($stored); //again something like: "��I݂6B{�M [r"