Using Open SSL to manage Your Keys

Friday, October 17, 2008

When it comes to WS-Security, for most of the operations, you will need to have either a certificate, or a key or both. Or you will need to provide a key store. WSF/PHP uses Open SSL library underneath to build WS-Security. Therefore knowing how to work with Open SSL can be really useful.

Lets go through some of the important commands you need to know to effectively get work done using Open SSL.

1. Generating a Certificate using Open SSL.

When generating a certificate, you have to decide whether you want an encrypted key or not. If you select the encrypted key option, your key will be protected by a passphrase.  This adds more security to your key since it will be difficult for some one stealing your key to use it. How ever you will need to provide this passphrase, every time you use the key. A self signed certificate is used to sign other certificates.

Use the command

openssl req -x509 -nodes -days 365 -newkey rsa:1024 -keyout mycert.pem -out mycert.pem

These options tells openssl to generate key length 1024  bits which is valid for 365 days and put both private key and certificate to a file named mycert.pem.


Now you will be prompt to answer a number of questions and then OpenSSL will generate you a self signed certificate.  Now if you open the mycert.pem you will see both the private key and the certificate stored there. If you remove the -nodes option, you will be asked to provide a passphrase.

2. Generating a private key and a matching public key using RSA algorithm.

It is sometimes necessary to generate the private key and public keys separately.

You can generate an RSA public key using the option genrsa.

openssl genrsa -out mykey.pem 2048

This generates a rsa private key with 2048 bits.

Using rsa option, you can get the corresponding public key.

openssl rsa -in mykey.pem -pubout

3. Creating a PKCS12 Keystore and adding keys to it.

openssl pkcs12 -export  -out mycert.pfx -in mycert.pem  -name "My Keystore"

This command generates a PKCS12  key store by exporting the above generated certificate. Here you will be asked for a passphrase as well.