Please help with openssl_pkcs7_encrypt() and decrypt()
Posted: Thu Aug 09, 2007 4:37 pm
For quite a while I have been trying to get the two functions, openssl_pkcs7_encrypt() and openssl_pkcs7_decrypt(), to work without much success.
Here is my code:
Which outputs the following webpage:
Testing openssl_public_encrypt/openssl_private_decrypt
Source: Hello World
Encrypted: 5à‚£ƒ•”êx2 ¤ÝÑr}ì/*¶V%™ÜOmY§"8éöFdmôÞ»Jä}V
Here is my code:
Code: Select all
<?php
echo "<h3>Testing openssl_public_encrypt/openssl_private_decrypt</h3>";
$source = "Hello World";
echo "<b>Source:</b> $source<br>";
$fp = fopen("./test.crt", "r");
$pubKey = fread($fp, 8192);
fclose($fp);
openssl_public_encrypt($source, $cryptText, $pubKey);
echo "<br><b>Encrypted:</b> $cryptText<br>";
$fp = fopen("./test.key", "r");
$privKey = fread($fp, 8192);
fclose($fp);
$passPhrase = "test";
$privKeyRes = openssl_get_privatekey($privKey, $passPhrase);
openssl_private_decrypt($cryptText, $decrypted, $privKeyRes);
echo "<br><b>Decrypted:</b> $decrypted<br><br>";
echo "<br><h3>Testing openssl_pkcs7_encrypt/openssl_pkcs7_decrypt</h3>";
$data = <<<EOF
Hello World
EOF;
$cert = implode("", file("test.crt"));
$key = implode("", file("test.key"));
$tempFileName = tempnam("temp", "b2b");
$datFile = $tempFileName . ".dat";
$encFile = $tempFileName . ".enc";
$decFile = $tempFileName . ".dec";
$fp = fopen($datFile, "w");
fwrite($fp, $data);
fclose($fp);
if (openssl_pkcs7_encrypt($datFile, $encFile, $cert, array())) {
echo "<b>Successfully encrypted: </b>";
$tempStr = file_get_contents($encFile);
echo "$tempStr<br><br>";
echo "<b>Encrypted string again, with \"\\n\" replaced with <br> and \"\\r\" replaced with [CR]:</b><br>";
$fp = fopen($encFile, 'r');
while (false !== ($char = fgetc($fp))) {
if ($char == "\n") {
echo "<br>";
}
else if ($char == "\r") {
echo "[CR]";
}
echo "$char";
}
if (openssl_pkcs7_decrypt($encFile, $decFile, $cert, $key)) {
echo "<br><b>Successfully decrypted: </b>";
$tempStr = file_get_contents($decFile);
echo $tempStr;
}
}
?>Which outputs the following webpage:
Testing openssl_public_encrypt/openssl_private_decrypt
Source: Hello World
Encrypted: 5à‚£ƒ•”êx2 ¤ÝÑr}ì/*¶V%™ÜOmY§"8éöFdmôÞ»Jä}V