Skip to content
Advertisement

How to decrypt data using phpseclib class Crypt_RSA that was encrypted by travist/jsencrypt

im using linux ubuntu server with nginx,mysql,php7.3

  1. I’m trying to encrypt message using public rsa key, that was generated on server side using phpseclib (http://phpseclib.sourceforge.net/)
<?php
//session_start();
$rsa = new Crypt_RSA(); 
extract($rsa->createKey()); 
$rsa->loadKey($privatekey); 
$_SESSION['pr']=(empty($_SESSION['pr'])) ? $rsa : $_SESSION['pr'];
$rsa->loadKey($publickey);
$_SESSION['pu']=(empty($_SESSION['pu'])) ? $rsa : $_SESSION['pu'];
?>
  1. Then i’m trying to use generated key to encrypt and decrypt message with JSEncrypt library (https://github.com/travist/jsencrypt), it works so far
<br /><input type="button" value="Show Encrypted" onclick="alert(crypted);"/>&nbsp;<input type="button" value="Show Decrypted" onclick="alert(decrypt);"/><br />
<script type="text/javascript">
var crypt = new JSEncrypt();
var public_key = '<?php echo der2pem($_SESSION["pu"], "RSA PUBLIC KEY";?>';
crypt.setPublicKey(public_key);
var input='i've got a power';
var crypted=crypt.encrypt(input);
var decrypt=crypt.decrypt(crypted);
alert(crypted);
alert(decrypt);
</script>
  1. And finally im trying to decrypt JSEencrypted message with private key using phpseclib rsa implemetation. Expecting to get original unencrypted message but all i got is Notice: Decryption error in enc/RSA.php on line 2507 Please help me out, i have tried to put b64 decoded string, hex string, tried to delete slashes or + symbols and nothinghelped. Point me into the right direction please im stucked like a bitch. Thanks in advance!
<?php
// here i put the crypted var showed in alert
$var=base64_decode('##put your variable here');

$rsa->loadKey($_SESSION['pr']);
$dec=$rsa->decrypt($var);
echo '<br />'.$dec;
?>

Hey, neubert! Thanks for the answer you really helped me to figure out the exact issue that i’ve got: when i use crypt.encrypt function without setting a key first it creates a key pair itself, and then setting it itself, so i will not be able to decrypt the message using keys saved in my php session. But the next problem was the pem rsa format that crypt.setKey function is requiring. So now i’d like to ask do you know how to convert b64 encoded $rsa into pem format, i have tried to add corresponding lines on both sides of key but it doesn’t help. Should i explode it to delimit into 64 bytes lines with “n” at the end of each one? Such a function has been found here

Advertisement

Answer

Try adding this before you perform the actual decryption operation in phpseclib:

$rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1);

phpseclib uses the more secure but less common OAEP padding, by default.

User contributions licensed under: CC BY-SA
3 People found this is helpful
Advertisement