Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
OpenSSL command line recipe for multi-public key file encryption. Any single private key paired to one of the public keys can decrypt the file.
#!/usr/bin/env bash
# Example of multiple key AES encryption for text files using the openssl v. 0.9.8+ command line utility
# Uses n public certs as key for MIME PKCS envelope, any individual private key can decrypt.
# If standard RSA ssh keys exist, these can be converted to public certs as well (and ssh keys can decrypt)
# To sign (and verify) the encrypted file, one of the private keys is required, see:
# for openssl smime examples
# or for cms utility (OpenSSL v. 1.0+)
# Author: Kenneth White
# Released under the terms of the MIT license:
# Basically: Feel free to use, just give credit please
# Alice runs this locally, then publishes/distributes her self-signed public cert (key stays private)
# Optionally, if local private key passphrase is required remove: -nodes
openssl req -x509 -newkey rsa:4096 -days 3650 -nodes -subj "/C=US/ST=*/L=*/O=*/OU=*/CN=Alice/" -keyout alice.key -out
# Ditto for Bob...
openssl req -x509 -newkey rsa:4096 -days 3650 -nodes -subj "/C=US/ST=*/L=*/O=*/OU=*/CN=Bob/" -keyout bob.key -out
# Ditto for Frank...
openssl req -x509 -newkey rsa:4096 -days 3650 -nodes -subj "/C=US/ST=*/L=*/O=*/OU=*/CN=Frank/" -keyout frank.key -out
# If you wanna get crazy, Carol can use an existing SSH private key to generate a public cert (and decrypt w/ her ssh key)
openssl req -x509 -new -key ~/.ssh/id_rsa -days 3650 -nodes -subj "/C=US/ST=*/L=*/O=*/OU=*/CN=Carol/" -out
# Central secrets repo
echo 'All our secretz are belong to us' > secrets.txt
echo 'Germans *love* David Hasselhoff!' >> secrets.txt
cat secrets.txt
# Encrypt it with multiple public certs (PKCS PEM base64 text format) in aes256 cbc mode
openssl smime -encrypt -aes256 -in secrets.txt -out secrets.txt.enc -outform PEM
cat secrets.txt.enc
# secrets.txt.enc file is safe to distribute
# Bob, Alice, Frank or Carol can now decrypt it with their private keys (SSL or SSH)
# Optionally: -out secrets.decrypted.txt
openssl smime -decrypt -in secrets.txt.enc -inform PEM -inkey alice.key

This comment has been minimized.

Copy link

@ayush191992 ayush191992 commented May 16, 2019

how can we achieve this through open ssl apis
openssl smime -encrypt -aes256 -in secrets.txt -out secrets.txt.enc -outform PEM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment