Category: OpenSSL


Encrypt files using your public key and OpenSSL

By polfilm,
==== GET PUBLIC KEY FROM CERT - CONVERT P12 to PEM
openssl pkcs12 -in my.client.cert.p12 -out my.client.cert.pem
Enter Import Password:
MAC verified OK
Enter PEM pass phrase:
Verifying - Enter PEM pass phrase:

=== GET PUBLIC KEY FROM CERT - EXTRACT PUBLIC KEY
openssl rsa -in my.client.cert.pem -pubout -out my.client.cert.pub
Enter pass phrase for my.client.cert.pem:
writing RSA key

=== ENCRYPT FILE - GENERATE RANDOM PASS
openssl rand -base64 40 -out pass.txt

=== ENCRYPT FILE - USE PASSWORD TO ENCRYPT FILE
openssl enc -e -aes-256-cbc -salt -pass file:pass.txt -in <filename> -out <filename>
e.g.
openssl enc -e -aes-256-cbc -salt -pass file:pass.txt -in somefile -out somefile.encrypted

=== ENCRYPT FILE - ENCRYPT PASS.TXT WITH PUBLIC KEY
openssl rsautl -encrypt -pubin -inkey <public key> -in <original file> -out <encrypted file>
e.g.
openssl rsautl -encrypt -pubin -inkey my.client.cert.pub -in pass.txt -out pass.encrypted

>> file is now encrypted
>> pass.txt can be deleted

=== DECRYPT FILE - DECRYPT PASSWORD
openssl rsautl -decrypt -inkey <pem file> -in <encrypted file> -out <original file>
e.g.
openssl rsautl -decrypt -inkey my.client.cert.pem -in pass.encrypted -out pass.txt

=== DECRYPT FILE - USE PASSWORD TO DECRYPT FILE
openssl enc -d -aes-256-cbc -pass file:pass.txt -in <filename>  -out <filename>
e.g.
openssl enc -d -aes-256-cbc -pass file:pass.txt -in somefile.encrypted -out somefile

>> delete pass.txt (no longer needed)