2
我想使用PHP和OpenSSL使用公鑰加密一些數據,然後再解密它。PHP加密/解密使用OpenSSL不爲我工作
我產生public.key和private.key使用此代碼:
// generate private key
$privateKey = openssl_pkey_new(array(
'private_key_bits' => 1024,
'private_key_type' => OPENSSL_KEYTYPE_RSA,
));
// write private key to file
openssl_pkey_export_to_file($privateKey, 'private.key');
// generate public key from private key
$publicKey = openssl_pkey_get_details($privateKey);
// write public key to file
file_put_contents('public.key', $publicKey['key']);
// clear key
openssl_free_key($privateKey);
我的代碼進行加密和解密基本上是直接從PHP文件:
// data to encrypt
$data = "This is a long string or other bit of data that i want to encrypt";
// ==== ENCRYPT ====
// read public key
$publicKey = file_get_contents("public.key");
$publicKey = openssl_get_publickey($publicKey);
// encrypt data using public key into $sealed
$sealed = '';
openssl_seal($data, $sealed, $ekeys, array($publicKey));
openssl_free_key($publicKey);
// ==== DECRYPT ====
// get private key to decrypt with
$privateKey = file_get_contents("private.key");
$privateKey = openssl_get_privatekey($privateKey);
// decrypt data using private key into $open
$open = '';
openssl_open($sealed, $open, $env_key, $privateKey);
openssl_free_key($privateKey);
// display decrypted data:
echo "<p>Decrypted data: ".$open;
任何人有任何線索爲什麼它不工作,或者至少有一種方法來查明發生了什麼錯誤?
首先的示例代碼,檢查所有變量的值,以確保它們包含的內容,你認爲他們應該包含:) – 2012-08-16 12:12:24
@Jack乾杯,是我認爲一切都應該如此。據我所知,它只是拒絕解密數據。我在這裏貼了一個例子:http://pastebin.com/HMGg7FSg – Rob 2012-08-16 12:22:22