Sarah Weinberger
Sarah Weinberger

Reputation: 15571

Unable to properly encrypt data in Javascript using jsbn

I am having trouble encrypting data in JavaScript using Tom Wu's jsbn library.

I wind up with an encrypted data, however when I try and decrypt the data on PHP, openssl_private_decrypt returns false.

Is it possible the way that I am encoding the public key?

Here is the JavaScript code that encrypts the data.

function encryptData(data)
{
    var $oDataEncrypted = "";

    // Do not forget to escape the lines:
    var $pem = "-----BEGIN PUBLIC KEY-----\nMIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCoEu5N3x/6aK7E4A9f+7AV/A9T\nT6zu5zdM6L+6XViYC6JssiV1JVE/x/5yd4mVrG8CFkOaF9QqOIFFnQnQw+O+5B/3\nRdoIAssExytGyjY7k11u9jKZI+xRslCxQRoQnUzEVE29Vr6TWUwpxrnpsl+z/5ej\n+Yk8UsMJRkBvmSMdDwIDAQAB\n-----END PUBLIC KEY-----";

    // Create the RSA object.
    var $key = RSA.getPublicKey($pem);

    $oDataEncrypted = RSA.encrypt(data, $key);

    return $oDataEncrypted;
}

One thought was the "\n" and that maybe JavaScript, unlike PHP, does not automatically understand the construct or the library does not.

I am using the latest files obtained at:

http://www-cs-students.stanford.edu/~tjw/jsbn/

https://github.com/ziyan/javascript-rsa/tree/master/src

For testing, I copy and pasted the encrypted value (using Visual Studio for the JavaScript side for testing) to my PHP file. I pass in my key to openssl_private_decrypt() and get a return of FALSE. Sadly, openssl_private_decrypt does not return a reason, and the JavaScript code appears to return a value and no errors get thrown or returned.

My guess is something with the public key, but obviously the problem could lie somewhere else.

Upvotes: 0

Views: 951

Answers (1)

Sarah Weinberger
Sarah Weinberger

Reputation: 15571

For posterity sake, I will give the answer. The answer has been in my face for a bit, just was too dense to realize it.

JavaScript encodes data in base-64, so the data must be decoded before PHP will recognize it. Therefore, on the PHP side, there needs to be a simple addition:

if(!openssl_private_decrypt(base64_decode($dataArg1), $sensitiveData, $key))

I wrapped the data argument in base64_decode().

Upvotes: 1

Related Questions