使用OpenSSL解密字符串只能在终端中使用,而不能在PHP脚本中使用 [英] Decrypting string using OpenSSL works in terminal but not in PHP script
问题描述
我正在尝试解密文件,我可以使用以下字符串在终端中使用OpenSSL对其进行解密.
I'm trying to decrypt a file, I can decrypt it using OpenSSL in the terminal using the following string.
openssl -enc -d -aes-192-ecb -in file.crypt -out file -K 0123456789abcdef -iv 0
但是,我想用PHP解密此文件.我有以下代码:
However, I want to decrypt this file in PHP. I have the following code:
$file = file_get_contents('file.crypt');
$key = 0123456789abcdef;
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_192, $key, $file, MCRYPT_MODE_ECB);
print_r($data);
很明显,我丢失了一些东西,因为PHP脚本正在返回数据,而不是纯文本.
Obviously I'm missing something as the PHP script is returning data, but not the plain-text.
我尝试使用MCRYPT_RIJNDAEL_128,但是没有运气.如果您能看到我在做什么错,请告诉我.预先感谢.
I have tried using MCRYPT_RIJNDAEL_128 but with no luck. Please let me know if you can see what I'm doing wrong. Thanks in advance.
更新
我已使用以下方法成功解密了文件:
I have successfully decrypted my file using the following:
$key = pack('H*', '0123456789abcdef'); //In >= PHP 5.4 you can use hex2bin() I think.
$data = mcrypt_decrypt(MCRYPT_RIJNDAEL_128, $key, $file, MCRYPT_MODE_ECB);
推荐答案
openssl
中的键和IV用十六进制表示(因此太短了),而PHP中的键和IV用作字符值.请在openssl中为AES密钥指定32、48或64个十六进制数字,在PHP中为16、24或32字节指定相同的值. IV必须始终为32个十六进制数字或16个字节,因为这是AES的块大小.
The keys and IV in openssl
are in hexadecimals (and therefore too short) and those in PHP are used as character values. Please specify 32, 48 or 64 hexadecimal digits for AES keys in openssl and the same value in 16, 24 or 32 bytes in PHP. The IV should always be 32 hex digits or 16 bytes as that is the block size of AES.
您应该始终将MCRYPT_RIJNDAEL_128
用作128,因为其中存在算法的块大小-而不是密钥大小-MCRYPT_RIJNDAEL_192
和MCRYPT_RIJNDAEL_256
算法没有实现em.
You should always use MCRYPT_RIJNDAEL_128
as the 128 in there is the block size - not the key size - of the algorithm, The MCRYPT_RIJNDAEL_192
and MCRYPT_RIJNDAEL_256
algorithms do not implement AES.
此外,openssl的默认设置为PKCS#7填充,请检查mcrypt_encrypt
注释部分以了解PHP的PKCS填充的实现-默认情况下不提供该功能.
Also, openssl defaults to PKCS#7 padding, check the mcrypt_encrypt
comments section for implementation of PKCS padding for PHP - it does not provide it by default.
这篇关于使用OpenSSL解密字符串只能在终端中使用,而不能在PHP脚本中使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!