#!/bin/bash
set -e
set -x
# Generate 1024 bits rsa private key and output to file "test.key".
# This private key was encrypted by AES256 with the password "hkp".
openssl genrsa -aes256 -passout pass:hkp   -out test.key 1024
# Generate public key from the private key file "test.key" and output it to public key file "test.pub"
# Since the private key has been encrypted, so we need to pass in the password to decrypt it.
openssl rsa -passin pass:hkp -in test.key -pubout -out test.pub
# Encrypt the plain message from "plain.txt" and output to cipher file "cipher.txt" with public key.
# NB., if encrypt with public key, the option "-pubin" should be provided,
# if encrypt with private key, the password should be provided if needed.
#
# As per the manual of openssl,
# -encrypt encrypt with public key
# -decrypt decrypt with private key
# So even we use private key file "test.key" to encrypt the message, openssl only use the public part of "test.key"
openssl rsautl -encrypt -pubin -inkey test.pub -in plain.txt -out cipher.txt
openssl rsautl -encrypt -passin pass:hkp -inkey test.key -in plain.txt -out cipher_by_private_key_file.txt
# Decrypt the cipher message from "cipher.txt" and output the decrypted message into "decrypt.txt" with private key.
# Since the private key has been encrypted, so we need to pass in the password to decrypt it.
openssl rsautl -decrypt -inkey test.key -passin pass:hkp -in cipher.txt -out decrypt.txt
openssl rsautl -decrypt -inkey test.key -passin pass:hkp -in cipher_by_private_key_file.txt -out decrypt_also_by_private_key_file.txt
# Sign the digest of message with sha256 as the digest algorithm and output the signature to "plain.sig"
openssl dgst -sign test.key -passin pass:hkp -sha256 -out plain.sig plain.txt
# Verify the signature with the public key from public key file "test.pub",
# Please be note that, the signature is of the digest of the message from file "plain.txt".
openssl dgst -verify test.pub -sha256 -signature plain.sig plain.txt
# Since the public key can be retrieved from private key file,
# so openssl also support verify signature via private key file.
openssl dgst -prverify test.key -passin pass:hkp -sha256 -signature plain.sig plain.txt