Question

I'm having trouble to decrypt a cipher text in client side/javascript which is encrypted in server side/PHP.

For encryption in PHP, I'm using the phpseclib and here is my sample code block:

define('PUK', 'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDwMKuLMVuo7vHDwFCbpgxx+RNf xSVC2GRWq9rW0fl4snnhRdrpprPRUO1RMV0wA/ao+fvzi1Sl0lcws3srpe28iLAj Wh5vFM/pFstwzjoHBv/6n4rQouIVy2NT18aFrxlQUCs4DHy5eOo21MjQXrgHwCeP HEc7OK+VpaQ/yKKX8wIDAQAB');
include ('Crypt/RSA.php');

$rsa = new Crypt_RSA();

$plaintext = 'My Test Msg';

$rsa -> loadKey(PUK);
$ciphertext = $rsa -> encrypt($plaintext);
//echo $ciphertext;//This also not working!
//echo strrev(base64_encode($ciphertext)); //this is also not working! ref: http://www.frostjedi.com/phpbb3/viewtopic.php?f=46&t=141187
echo base64_encode($ciphertext);

For decryption in client side/Javascript, I'm using "jsencrypt" and here is the code block:

var decrypt = new JSEncrypt();
decrypt.setPrivateKey('MIICXQIBAAKBgQDwMKuLMVuo7vHDwFCbpgxx+RNfxSVC2GRWq9rW0fl4snnhRdrp prPRUO1RMV0wA/ao+fvzi1Sl0lcws3srpe28iLAjWh5vFM/pFstwzjoHBv/6n4rQ ouIVy2NT18aFrxlQUCs4DHy5eOo21MjQXrgHwCePHEc7OK+VpaQ/yKKX8wIDAQAB AoGBAL2EuaZvwLIwL6VUVoYp5AH+FVJo3Ti8Q5e7rEX6kgyxTsf4dX4NIi9T2p1J BQ2A4xx7e1i0pIreyBtOUy6ik0y7e3MlmZidG91pz2KllQqwAMKrOZgPTBWBF7fr xIZERfOlZcIRrqp8ECbeHDyO6fUbfQm+o7vkxMypwjixBslJAkEA+mF8Sxvw+7D6 ntev+XsYj9Xp4wumqR2hK4WcXAAWbFmcd29tgTMKfcgw0Ru6FCGQdUvqu61PniS4 ie+u6zPORwJBAPWUos5KvEixkgSUY0PZOQavRwoXS1GEEvkjlFOyqWqUiKViT9iy UsXKxk3NAVMqIdF5RdAQ/ob9NxtxiuSxYvUCQQDUfFsBWwsebsmieCVNslvb5YyC NOcRaqXWy6MwqJpfBYW2Doh+NxTWPki/japTX1C7WtwwvhpteXhrB1AJJ4QNAkB1 RrsM6vHJgUsq9rYE07qA77lsHz2vuvPYmF4gLkTrie1LlYxt/pK6tCBJTSphzdAC mfh16XezfT8Q0wMyPWf1AkAxS//2T3J1g+dbG9dEKREcpwANxlFIEnOm9XsFd2vO I6Jr0ksaS4o0IeUBDWmMFOgCWVPdJkGrlqlVPQ6P9owA');
var uncrypted = decrypt.decrypt(ciphertext); //The ciphertext is obtained from the server by an AJAX call.

BUT the "uncrypted" is found always to be null!

Please note that if I use the mentioned Private/Public key pair either in phpseclib or jsencrypt then it is working fine. The problem is creating only on encryption in PHP and decryption in Javascript.

It will be really appreciable if anyone can help me on this regard.

Was it helpful?

Solution

What happens if you encrypt in Javascript and try to decrypt in PHP? Does that work?

If not then if you could post the ciphertext produced by Java that'd be helpful. That'd give us a chance to breakdown the encoding of the plaintext and see which padding method - if any - is being used.

That said, in lieu of having that, my guess, off hand, would be that you need to do $rsa->setEncryptionMode(CRYPT_RSA_ENCRYPTION_PKCS1).

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top