Tuesday, February 19, 2013

Encrypting/decrypting files with openssl

If you want to encrypt and decrypt files using openssl command line tools, here is what you need to do.

First, you need to use your private key to generate a public key.

openssl rsa -in ~/.ssh/id_rsa -pubout ~/.ssh/id_rsa.public

That is not to be confused with SSH public. Once you have that you can encrypt a file using your public key:

> echo "example">~/.ssh/passwd
> openssl rsautl -encrypt -inkey ~/.ssh/id_rsa.public -pubin -in ~/.ssh/passwd -out ~/.ssh/.passwdenc
> openssl rsautl -decrypt -inkey ~/.ssh/id_rsa -in ~/.ssh/.passwdenc 
example


I find this useful when sharing scripts that require password and you don't want to store your password un-encrypted and you also don't want to have to remember to remove the password (if you did type in your password) before sharing it. I sometimes find it useful to create expect scripts to check multiple servers that do not support public/private key pair encryption and I don't want to put my clear text password in the script.