Wednesday, January 25, 2012

Encrypting Transmissions between JavaScript and PHP Part 1: Creating a useful OpenSSL RSA private/public key pair

I am working on configuring my web pages to encrypt a user's password when they log in to a web page.  At the moment I do not have the luxury of using HTTPS so I am focusing on using JavaScript to encrypt just the password using a RSA public key and decrypting it on the server side in PHP using the private key.

I had a hard time finding instructions for creating OpenSSL private/public key pairs that covered everything all in one place so I figured I would document what I have learned so I don't have to search for it again in 4 years the next time I need to do it.

Assuming you already have the latest version of OpenSSL installed, run the following commands from the command line.  I am using 2048 bit keys, if you wish you may substitute a different number in the instructions below. Also, I am not encrypting the keys.  For my purposes it is pointless as the password would be stored with the key.

1.  openssl genrsa -out privateKey.pem -f4 2048

  • This creates the initial private key.  the -f4 option signifies that the public exponent should be 10001
2. openssl rsa -in privateKey.pem -out publicKey.pem -pubout

  • This derives a public key from our private key
3. openssl rsa -in privateKey.pem -out publicKey.modulus -modulus -noout

  • This derives the modulus from the private key

4. openssl req -new -x509 -key privateKey.pem -out privateKey.x509 -days 1095

  • x509 self signed certificate
5. openssl req -new -key privateKey.pem -out privateKey.csr

  • normal certificate request for if you need to get an official certificate


As a quick refresher, you use the private key for the following:

  • decrypt content encrypted with your public key
  • sign (encrypt) content to be verified with your public key
You use the public key for the following:

  • encrypt content to be decrypted by the private key
  • verify content signed by the private key
For my purposes, I will be using the public key to encrypt content sent from a user's web browser via javascript, and using the public key to decrypt it on the server side via PHP. Check out Part 2 Next!

1 comment:

ronbravo said...

Thank you so much for posting this. Spent two days researching how to do this, and I kept running into stumbling blocks and errors. Thanks again.