我在PHP中加密密码,并希望在另一个盒子上解密它。我没有运气,我宁愿能够从bash中解密它并回应它。下面是PHP中的一个测试片段。
$textToEncrypt = "My super secret information.";
$encryptionMethod = "AES-256-CBC";
$secretHash = "Testkey";
//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $secretHash);
//To Decrypt
$decryptedMessage = openssl_decrypt($encryptedMessage, $encryptionMethod, $secretHash);
//Result
echo "Encrypted: $encryptedMessage <br>Decrypted: $decryptedMessage";
我已尝试过多种方法在Ubuntu上解密它,甚至将数据存储到文件中并将其输出到文件中。尝试的命令是:
openssl aes-256-cbc -a -d -k Testkey -in foo.txt -out secrets.txt
其中foo.txt
是从PHP加密返回的值,secrets.txt
是输出。我怎么能这样做?
答案 0 :(得分:1)
重要的是,如评论中所述,没有IV的加密是危险的。事实上,PHP的当前版本将发出警告。 IV可以使用openssl_random_pseudo_bytes()
函数随机生成,并与加密文本一起以明文形式传输。它们不必是秘密,重要的是不要重复使用相同的密钥和IV组合,并且随机有IV。
因此,如果你看看the source for the function,那么它不会将 password
参数作为密码传递,而是作为密钥传递。因此,要在命令行上使用openssl
,它必须是十六进制并传递给-K
选项,而不是-k
选项。但是,你会收到一个错误,说“iv undefined”,所以你的PHP需要调整为包含一个:
$textToEncrypt = "My super secret information.";
$encryptionMethod = "AES-256-CBC";
$key = "Testkey";
$iv = "4toij35unvouqo{2"; //must be 16 bytes
$keyHex = unpack("H*", $key)[1];
$ivHex = unpack("H*", $iv)[1];
//To encrypt
$encryptedMessage = openssl_encrypt($textToEncrypt, $encryptionMethod, $key, 0, $iv);
//To Decrypt
$decryptedMessage = openssl_decrypt($encryptedMessage, $encryptionMethod, $key, 0, $iv);
//Result
echo "Hex key: $keyHex<br/>\nHex IV: $ivHex<br/>\nEncrypted: $encryptedMessage<br/>\nDecrypted: $decryptedMessage<br/>\n";
获得这些详细信息后,您可以从命令行解密(在此处重复使用PHP变量名称):
echo -n "$encryptedMessage" | openssl aes-256-cbc -d -a -K "$keyHex" -iv "$ivHex"
答案 1 :(得分:0)
相反的方式
#!/bin/bash
# create in bash keys
echo "generating private key"
openssl genrsa -out privkey.pem 2048
echo "signing private key"
openssl req -new -key privkey.pem -out certreq.csr -subj "/C=RO/ST=AB L=AB/O=None/OU=Department/CN=someweb.com"
echo "create a sign request"
openssl x509 -req -in certreq.csr -signkey privkey.pem -out newcert.pem
# end-of-bash-script
cp ./privkey.pem /path/to/apache/root/<some>
加密一些json文件
openssl smime -encrypt -aes256 -in ./json.txt -binary -outform DER -out ./json.xxx newcert.pem
# test decrypt here in bash
# openssl smime -decrypt -in json.xxx -inform DER -inkey privkey.pem -out json.dec
将其作为二进制文件发布到php
curl --request POST --data-binary @./json.xxx http://localhost/<some/>json.php
然后是json.php脚本@apache root
<?php
$rkey = file_get_contents("/var/www/html/privkey.pem");
$pkey = file_get_contents("/var/www/html/newcert.pem");
$data = file_get_contents("php://input");
$fenc = tempnam("", "enc");
$fdec = tempnam("", "dec");
file_put_contents($fenc,$data);
// openssl_pkcs7_decrypt ($fenc , $fdec , $pkey, $rkey ); unable to coerce parameter 3 to x509 cert
system("openssl smime -decrypt -in ${fenc} -inform DER -inkey privkey.pem -out ${fdec}");
echo file_get_contents($fdec);
?>