Asymmetric cryptography (also known as public key cryptography) is a cryptographic system that uses a public and private key pair. Public key can be used for data encryption and private key can be used for data decryption. Data encrypted with the public key can only be decrypted with the private key. This tutorial shows how to encrypt and decrypt files with public and private key using OpenSSL.
Let's say we have the following public key and private key:
-----BEGIN PUBLIC KEY-----
MFwwDQYJKoZIhvcNAQEBBQADSwAwSAJBAN/ovAmhoNOnE2VoJeUunpEB+CwTyPbK
I8VnQ+rLa75riBtmfYrGdUD8Cv/p+ioL86xwSvX+HYXnkPffEXc7IlUCAwEAAQ==
-----END PUBLIC KEY-----
-----BEGIN PRIVATE KEY-----
MIIBVQIBADANBgkqhkiG9w0BAQEFAASCAT8wggE7AgEAAkEA3+i8CaGg06cTZWgl
5S6ekQH4LBPI9sojxWdD6strvmuIG2Z9isZ1QPwK/+n6KgvzrHBK9f4dheeQ998R
dzsiVQIDAQABAkA3eyS0wj7mkvykYPUa371csv86dMCUHixU6qySjkspSGcvdqNQ
UuAfRJ97n8m8wkNSHhF2HIWH2lPdC/MsZX/VAiEA8QLAZXzsUiEIQ04enLZRq0cv
YkD8mLyXVpT56ZrdEDsCIQDt1bMedIH1kCcAvg4PHAugXw1NeJSvpOpUqOyPwmB+
rwIhAJDhq5EW4OWaT+JOAt8IRt4k49o34OFcdcmpsvZ4jy3jAiA7n+2N3wuNspv0
lbEUnKVViT7egzJTbnbIzqivyb1DRQIhAKbr3cYY4mk0HKFQg3oEhWi2stSPulYz
KNkxLcXmqXjr
-----END PRIVATE KEY-----
The openssl pkeyutl
command can be used for encrypting and decrypting input data using public and private key. To encrypt a file named data.txt
with public key test.pub
, run the following command:
openssl pkeyutl -encrypt -pubin -inkey test.pub -in data.txt -out data.enc.txt
The meaning of options:
-encrypt
- encrypts the input data with public key.-pubin
- reads public key instead of a private key.-inkey test.pub
- specifies the filename to read a public key.-in data.txt
- specifies input filename to read data.-out data.enc.txt
- specifies output filename to write encrypted data.
To decrypt a file named data.enc.txt
with private key test.key
, run the following command:
openssl pkeyutl -decrypt -inkey test.key -in data.enc.txt -out test.out.txt
The meaning of options:
-decrypt
- decrypts the input data with private key.-inkey test.key
- specifies the filename to read a private key.-in data.enc.txt
- specifies input filename to read encrypted data.-out test.out.txt
- specifies output filename to write data.
Leave a Comment
Cancel reply