· 8 years ago · Jan 16, 2018, 10:54 AM
1### ENCRYPT A FILE USING A PUBLIC SSH KEY
2
3Generate the symmetric key (32 bytes gives us the 256 bit key):
4
5```
6$ openssl rand 32 -out secret.key
7
8```
9You should only use this key this one time, by the way. If you send something to the recipient at another time, don’t reuse it.
10
11Encrypt the file you’re sending, using the generated symmetric key:
12
13```
14$ openssl aes-256-cbc -in secretfile.txt -out secretfile.txt.enc -pass file:secret.key
15```
16
17In this example secretfile.txt is the unencrypted secret file, and secretfile.txt.enc is the encrypted file. The encrypted file can be named whatever you like.
18
19Encrypt the symmetric key, using the recipient’s public SSH key:
20
21```
22$ openssl rsautl -encrypt -oaep -pubin -inkey <(ssh-keygen -e -f recipients-key.pub -m PKCS8) -in secret.key -out secret.key.enc
23```
24Replace recipients-key.pub with the recipient’s public SSH key.
25
26Delete the unencrypted symmetric key, so you don’t leave it around:
27
28```
29$ rm secret.key
30```
31Now you can send the encrypted secret file (secretfile.txt.enc) and the encrypted symmetric key (secret.key.enc) to the recipient. It is even safe to upload the files to a public file sharing service and tell the recipient to download them from there.
32
33DECRYPT A FILE ENCRYPTED WITH A PUBLIC SSH KEY
34First decrypt the symmetric.key:
35
36```
37$ openssl rsautl -decrypt -oaep -inkey ~/.ssh/id_rsa -in secret.key.enc -out secret.key
38```
39The recipient should replace ~/.ssh/id_rsa with the path to their secret key if needed. But this is the path to where it usually is located.
40
41Now the secret file can be decrypted, using the symmetric key:
42
43```
44$ openssl aes-256-cbc -d -in secretfile.txt.enc -out secretfile.txt -pass file:secret.key
45```
46Again, here the encrypted file is secretfile.txt.enc and the unencrypted file will be named secretfile.txt