$publicKey = "../ssh/public/pub"; $plaintext = "String to encrypt";
$pubKey = openssl_pkey_get_public($publicKey);
openssl_public_encrypt($plaintext, $encrypted, $pubKey);
echo $encrypted; //encrypted string
above code generating following error
openssl_public_encrypt() [http://php.net/function.openssl-public-encrypt]: key parameter is not a valid public key [APP/controllers/supportservice_controller.php, line 144]
I created the keys with openssl using:
generate a 1024 bit rsa private key, ask for a passphrase to encrypt it and save to file openssl genrsa -des3 -out /path/to/privatekey 1024
generate the public key for the private key and save to file
openssl rsa -in /path/to/privatekey -pubout -out /path/to/publickey
In my case,I Splited the public key into mutiple lines,solved the problem.
PHP Version 7.1.17
$publicKey = "-----BEGIN PUBLIC KEY-----\n" . wordwrap($publicKey, 64, "\n", true) . "\n-----END PUBLIC KEY-----";
$str = "str to be encrypted";
$opensslPublicEncrypt = openssl_public_encrypt($str, $encrypted, $publicKey);
In PHP 7.x and new versions of phpseclib (a pure PHP RSA implementation) and using composer to install phpseclib, you can do this:
# Install the phpseclib from console
composer require phpseclib/phpseclib:~2.0
// In your php script:
use phpseclib\Crypt\RSA;
$rsa = new RSA();
$rsa->loadKey($publicKey); # $publicKey is an string like "QEFAAOCAQ8AMIIBCgKCAQEAoHcbG....."
$plaintext = '...';
$ciphertext = $rsa->encrypt($plaintext);
var_dump($ciphertext);
#to decrypt:
$rsa->loadKey('...'); // private key
echo $rsa->decrypt($ciphertext);```
Like this you can add your key and encrypt the text
$data = json_decode(file_get_contents('php://input'), true);
$enctext = $data['enctext'];
$pubkey = '-----BEGIN PUBLIC KEY-----
PUBLIC KEY PLACED HERE
-----END PUBLIC KEY-----';
openssl_public_encrypt($enctext, $crypted, $pubkey);
$data['enctext'] = $enctext;
$data['Encryption_text'] = base64_encode($crypted);
echo json_encode($data);
exit;
Or instead of this you can also call a .cert file of public key
$fp=fopen("publickey.crt","r");
$pub_key_string=fread($fp,8192);
fclose($fp);
$key_resource = openssl_get_publickey($pub_key_string);
openssl_public_encrypt($enctext, $crypted, $key_resource );
$data['enctext'] = $enctext;
$data['Encryption_text'] = base64_encode($crypted);
echo json_encode($data);
exit;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With