Skip to content

Instantly share code, notes, and snippets.

@bdargan
Last active December 16, 2022 07:25
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save bdargan/9240659 to your computer and use it in GitHub Desktop.
Save bdargan/9240659 to your computer and use it in GitHub Desktop.
Manually encrypt files with openssl.
#!/bin/bash
rm -f content
rm *.enc
rm *.pem
rm keyfile
rm *.b64
rm *.dec
echo "generate: data-key for this content transfer"
openssl rand 32 -out keyfile
echo "generate: private key of the Recipient (Not normally known)"
openssl genrsa -out recipient-key.pem 2048
echo "generate: public key (Provided by recipient)"
openssl rsa -in recipient-key.pem -out recipient-key.pub.pem -outform PEM -pubout
echo "generate: sample 2Mb 'content' file"
dd if=/dev/urandom bs=2097152 count=1 2>/dev/null | uuencode - | grep -v begin | cut -b 2-2097154 > content
echo -n "content fingerprint:"
md5 content
echo "encrypt content: content with keyfile: NOTE: check the keyfile size"
openssl enc -aes-256-cbc -a -kfile keyfile -in content -out content.enc
echo "generate: mail friendly attachment. base64 encode content, if needed to mail the file"
openssl base64 -e -in content.enc -out content.enc.b64
echo "encrypt: keyfile with public key of recipient"
openssl rsautl -encrypt -pubin -inkey recipient-key.pub.pem -in keyfile -out keyfile.enc
echo "generate: mail friendly recipient only key"
openssl base64 -in keyfile.enc -out keyfile.enc.b64
echo "info: ================= Encrypted Content Summary ================="
echo "info: content encrypted: content --> (Encrypted with keyfile) --> content.enc --> (base64) --> content.enc.b64"
echo "info: content data-key encrypted: keyfile --> (encrypted with Recipients Public Key) --> keyfile.enc --> (base64) --> keyfile.enc.b64"
echo "info: ================= Decrypt Content Process ================="
echo "info: keyfile.enc --> (decrypt using Recipient Private Key) --> keyfile.dec"
echo "info: content.enc --> (decrypt using keyfile.dec data key) --> content.dec"
echo "decrypt: keyfile"
openssl rsautl -decrypt -inkey recipient-key.pem -in keyfile.enc -out keyfile.dec
#openssl rsautl -decrypt -inkey recipient-key.pem -in keyfile.enc.b64 -out keyfile.dec.b64
echo "fingerprint of plaintext and decrypted cipher keyfile"
md5 keyfile keyfile.dec
echo "decrypt: encrypted content"
openssl enc -d -aes-256-cbc -a -kfile keyfile.dec -in content.enc -out content.dec
echo "fingerprint: check all content files"
md5 content content.dec
@seguri
Copy link

seguri commented Apr 30, 2019

Isn't content.enc already encoded in base64, thanks to openssl enc -a?

@Reboot1970
Copy link

| openssl enc -base64 -A

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