-1

I have generated two files cert.pem and key.pem using OpenSSL command req -x509 -newkey rsa:4096 -keyout key.pem -out cert.pem -days 365 Now I want to get public key from cert.pem file and private key from key.pem file. I have tried various methods but those method doesn't work for me. I am gonna use these keys for encryption/decryption (Asymmetric). I will use public key for encryption and private key for decryption. Can somebody provide me methods/code to get those keys from those files.

1 Answers1

0

You can make a public key from private key by this commend. you need phrase if you entered it during creating private key.

$ openssl rsa -in key.pem -pubout > public_key.pem

You can see the content of public key

$ cat public_key.pem

Now you ready to encryption. I will use plain text with simple message

$ echo 'secret message' > plain.txt

It makes to encrypt text

$ openssl enc -aes256 -base64 -e -in plain.txt -out cipher.txt

you needs to enter password during it. It's -e is to encrypt the -in file is input file.

$ cat cipher.txt
U2FsdGVkX18JKAGN3ECDpB0v1wtNdIuOxf8RYz8uMP4=

Finally you can make a decryption by this commend

$ openssl enc -aes256 -base64 -d -in cipher.txt -out plain_back.txt
$ cat plain_back.txt
secret message

Also you can make a signature file with certification file. I will make zip file first with plain.txt

$ zip data.zip plain.txt

To sign a data file , OpenSSL digest (dgst) command is used. you needs to enter pass phrase for key.pem

$ openssl dgst -sign key.pem -keyform PEM -sha256 -out data.zip.sign -binary data.zip

The digital signature can also be verified using the same openssl dgst command.

$ openssl dgst -verify public_key.pem -keyform PEM -sha256 -signature data.zip.sign -binary data.zip
Verified OK
Bench Vue
  • 5,257
  • 2
  • 10
  • 14
  • Did I miss something ? The poster wanted to use the public/private keys for encryption and decryption but you are using AES with a passphrase and not the asymmetric keys. – Michael Fehr Aug 21 '22 at 06:37
  • This is encrypt by public key example. https://raymii.org/s/tutorials/Encrypt_and_decrypt_files_to_public_keys_via_the_OpenSSL_Command_Line.html – Bench Vue Aug 21 '22 at 10:51