PHP RSA encryption using private key and PKCS1

Udinesio picture Udinesio · Jan 4, 2011 · Viewed 12.4k times · Source

I need to encrypt a string using RSA, PKCS1, a private key and PHP. I could not find even a terminal command which can be used with exec(). Does anyone knows how to do it?

Thanks!

Answer

user530167 picture user530167 · Jan 9, 2011

Try phpseclib, a pure PHP RSA implementation:

<?php
include('Crypt/RSA.php');

$rsa = new Crypt_RSA();
//extract($rsa->createKey());

$plaintext = 'terrafrost';

$rsa->loadKey($privatekey);
$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);
$ciphertext = $rsa->encrypt($plaintext);

echo $plaintext;
?>

Security warning: If you're going to use phpseclib, make sure you follow the best practices for RSA encryption. See also this answer for more details and an alternative approach.