I'm trying to decrypt a string using phpseclib.
My hashed string is being generated from a javascript library called jsencrypt. The result of the encryption is saved in a database.
Afterwards I'm using phpseclib3 to try and decrypt the string using this:
<?php
require_once ("vendor/autoload.php"); // i used composer to install phpseclib
use phpseclib3\Crypt\PublicKeyLoader;
use phpseclib3\Crypt\RSA;
$private_key = RSA::loadFormat('PKCS8', file_get_contents('key.pem'), $password = false);
$key = PublicKeyLoader::load($private_key)->withHash('sha512/256')->withMGFHash('sha512/256');
$hashed_string = base64_decode("...");
echo $key->decrypt($hashed_string);
?>
But when I run the code I get the following error:
Fatal error: Uncaught LengthException: Ciphertext representative too long in /vendor/phpseclib/phpseclib/phpseclib/Crypt/RSA/PrivateKey.php:389
I've also tried decrypting the string using openssl_decrypt
with no luck:
$privateKey = '-----BEGIN RSA PRIVATE KEY-----
PRIVATE KEY HERE...
-----END RSA PRIVATE KEY-----';
$encrypt_method = "AES-256-CBC";
$plain_text = openssl_decrypt('...', $encrypt_method, $privateKey, 0);
echo $plain_text;
Does anyone know how I can go about decrypting the hashed string?
You need to use PKCS1 padding. eg.
<?php
require_once ("vendor/autoload.php"); // i used composer to install phpseclib
use phpseclib3\Crypt\PublicKeyLoader;
$key = PublicKeyLoader::load(file_get_contents('key.pem'))->withPadding(RSA::ENCRYPTION_PKCS1);
$hashed_string = base64_decode("...");
echo $key->decrypt($hashed_string);
?>
Using a key generated from http://travistidwell.com/jsencrypt/demo/ :
$key = PublicKeyLoader::load('-----BEGIN RSA PRIVATE KEY-----
MIICWgIBAAKBgEajNAye2k3A60i6t51YgBoWOvc8y8+mhYVwt9Zge/e/e8k1Qk3g
XD2qmnGaztayXF5k52KyuhmOOipDph2m9ZWG3Xld76W5itkdQpWlojOQhABF8KWt
3pGTHdo7CyrxSDUpJLO6XtoMGrMox28muochErx+WdAnLreB9KZ3aJWlAgMBAAEC
gYAOKM7ZLMqTxXUkehEuYDwlfolJYA12zWl8azDery6KZf7ZQWzOEYhL8DPPS/nk
PZKYdV+QgEUftEvihvb4gKw/nAM0VPUjDQYpyCmilU9kIwrBwFSEEKYAKnzIn/9R
muWBMY0ayMAKDvvHEf2lplhEDMcOEXugA8zbE5PX8RVmjQJBAIiCEIdmimUAytEp
I0zYyWPnhy1t5QU4ISPV+fPz/reyexz2MnntaC/hUadIXyCnfZ7a1zMLRoxjssiO
2euGrPsCQQCEeEhPqEQm+YFmegJqNWcWPgYaAYvii2oXiDNG4JP9HV+lhMReGxAY
A2anqEPW9OIV8mOFJmd5iAZVS3ZHdQXfAkBDTIxFlMIqJYfYMoXavw4amOzF8uXz
+sYr2rROFz6+5dlYX/BmuCqjYFxXMpDjkm+WP6HU4nw3fneH9RVuzoi9AkA4irKq
tXKphBPUbr17IeInXz/xd7mCb+lPtAXW+eKQxineF0ZNuJVs+n6ljy+tn4akwXnz
CkpeWE4DuBr7MxrXAkBGLldtzDH3/71j8j3/wmPlW4mtz9ujutAA74HmkdrSxq/F
mN3Iu9ZArkR781R9PelP1q5PYc3cT+lsx+gfJv8p
-----END RSA PRIVATE KEY-----');
$key = $key->withPadding(RSA::ENCRYPTION_PKCS1);
echo $key->decrypt(base64_decode('JXqzrAxLvkWUc97SiL/DUZpx+miLzig6Bzp0zwrrPItETUk2rundbBu0WSyexhK586Xr9WOJVx/L7jiCzMyM8RImFPLPOoQqdPbCLDX5cARldn6oEr+5i60M1hSoYMfy6fr97ARAw04KGXRU6UjwEl869ghqSNxJ6+YxwggSwZo='));