Skip to content

Instantly share code, notes, and snippets.

@trevorrjohn
Last active July 28, 2021 01:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save trevorrjohn/aa4211c06f7d5cb459ef11e144580a9b to your computer and use it in GitHub Desktop.
Save trevorrjohn/aa4211c06f7d5cb459ef11e144580a9b to your computer and use it in GitHub Desktop.
Encrypt file using private public key

Context: "User A" has a password in a text file that he needs to share with "User B".

  1. User A and User B - Download and install openssl
% brew update && brew install openssl
  1. User B - Generate a public key
% ssh-keygen -o
  1. User B - Convert your public AND private key to .pem
% # public key
% openssl rsa -in ~/.ssh/id_rsa -outform pem > ~/.ssh/id_rsa.pem
% # private key
% openssl rsa -in ~/.ssh/id_rsa -pubout -outform pem > ~/.ssh/id_rsa.pub.pem
  1. User B - Send public key to User A (id_rsa.pub.pem)

  2. User A - Generate a random key

% openssl rand -base64 32 > key.bin
  1. User A - Encrypt the random key
% openssl rsautl -encrypt -inkey ~/.ssh/id_rsa.pub.pem -pubin -in key.bin -out key.bin.enc 
  1. User A - Encrypt the file you are trying to keep secret
% openssl enc -aes-256-cbc -md sha512 -pbkdf2 -iter 100000 -salt -in ${secret_file} -out ${secret_file}.enc -pass file:./key.bin
  1. User A - Send encryped files to User B (${secret_file}.enc and key.bin.enc)

  2. User B - Decrept the key and file

% # first the key
% openssl rsautl -decrypt -inkey id_rsa.pem -in key.bin.enc -out key.bin
% # then the actual file
% openssl enc -d -aes-256-cbc -md sha512 -pbkdf2 -iter 100000 -salt -in ${secret_file}.enc -out ${secret_file} -pass file:./key.bin 
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment