Reputation: 4383
I generate public and private keys for RSA by
openssl genrsa -des3 -out private.pem 2048 openssl rsa -in private.pem -out public.pem -outform PEM -pubout
and use following php code to encrypt and decrypt data.
<?php
$plaintext = 'Hello';
$publicKey = openssl_pkey_get_public('file://public.pem');
$encrypted = '';
if (!openssl_public_encrypt($plaintext, $encrypted, $publicKey))
die('Failed to encrypt data');
var_dump($encrypted);
if (!$privateKey = openssl_pkey_get_private('file://private.pem', '123456789'))
die('Private Key failed');
$decrypted = '';
if (openssl_open($encrypted, $decrypted, $envelope, $privateKey) === FALSE)
die('Failed to decrypt data');
?>
it will encrypt data ,but to decrypt data it doesn't work and show Failed to decrypt data
it will show some thing like following result
string(256) "y)ù¿5_÷q$çD±!‘[’ÓcÜC$Gèïü*ÞEÇGm>ËÂïQÄ„ð½i=é¨Zs€© |T²»Z”k( ráëµ1,r]o –Òll'T¾i¹Bò}Æ1sËèÝwœÒ„Ä–È‹\1{S'ÆY³Ïà^hŽ™©XO%f7‘Bþ®Ra.ªÜäÆô¼'©³#Ý.H9…ŒÏ\6°ÆýþÆJµ^ðŠØÆr£Ô&ü—Ý*ýÄq ƒÝcÓÚAçOmœi\Ê¿›ãB~ZP1ŒÑÔâ¨S…6—êQ–²x¥^0´Íº(d?G•ÚIWå¡Ä" Failed to decrypt data
Upvotes: 1
Views: 2027
Reputation: 104020
If you're using openssl_public_encrypt()
to encrypt your data, you need to use openssl_private_decrypt()
to decrypt the data.
openssl_open()
is for use with openssl_seal()
.
I'd recommend using the _open()
and _seal()
variants instead of the _public_encrypt()
and _private_decrypt()
variants -- the public key mechanisms are intended solely for session key transport and digital signatures. Public-key algorithms are intended for use on random data (or nearly-random data of message digests). Using non-random data with public key algorithms is definitely a mis-use of the algorithms.
Upvotes: 2