gpg session keys

In a previous post, I showed how the openssl rsautl tool can be used to encrypt small bits of data to an SSH host key.

One problem, is that rsautl cannot encrypt any data that is larger than the key size. One workaround however, is to use a symmetric key for the bulk encryption, and then use RSA to encrypt the smaller symmetric key.

Here’s how to do it.

Encrypt as normal, e.g. using gpg.

$ gpg --encrypt --armour --recipient 2639EAAB message.txt

Decrypt as normal, but display the symmetric key that was used to encrypt this specific message.

$ gpg --decrypt --show-session-key message.txt.asc
gpg: encrypted with rsa4096 key, ID C7AF8B1570728435, created 2014-02-13
      "Ben Cordero "
gpg: session key: '9:ACB9F52AC096A87D8CF6DDE9529BE590971670FD7CD098924BE2963DE0E25D43'
...

You can decrypt the message again, without the private key. Useful for escrow scenarios.

$ gpg --decrypt --override-session-key $SESSION_KEY message.txt.asc

These can be chained together to encrypt the session key to an RSA key.

$ echo $SESSION_KEY | openssl rsautl -inkey ~/.ssh/id_rsa.pub.pkcs8 -pubin -encrypt > session.key

or decrypt

$ gpg --decrypt --override-session-key $(openssl rsautl -inkey ~/.ssh/id_rsa -decrypt < session.key ) message.txt.asc