Sunday, February 5, 2012

Private Keys, Public Keys and Certificates

This is a quick tutorial that will cover

- Generate a private key

- Generate a .cert certificate with that private key

- Extract the public key from the certificate.

- Sign a file with private key and verify the signature with the public key

- Import the private key and certificate into a java keystore.


1. Generate a private key


openssl genrsa -out private.key 1024


2. Generate certificate


openssl req -new -x509 -days 365 -key private.key -out certificate.crt


That certificate is a good self signed certificate that is ready to distribute around for testing.


3. Extract public key from certificate


openssl x509 -in certificate.crt -pubkey > public.key


That will copy the certificate and the public key to the file... you need to edit the file and remove the part related to certificate and leave just the public key in the file.


4. We sign a file with private key.

openssl dgst -sha1 -sign private.key -out file_to_sign.sha1 file_to_sign


5. We verify the signature with the public key:


openssl dgst -sha1 -verify public.key -signature file_to_sign.sha1 file_to_sign


6. we import private key and certifcate to a java keystore


first we generate a p12 file


openssl pkcs12 -export -in certificate.crt -inkey private.key > server.p12


then we import this into the keystore


keytool -importkeystore -srckeystore server.p12 -destkeystore keystore.jks -srcstoretype pkcs12

No comments: