# File encryption using OpenSSL

## Symmetic encryption

For symmetic encryption, you can use the following:

To encrypt:

```
openssl aes-256-cbc -salt -a -e -in foo.txt -out foo.txt.enc
```

To decrypt:

```
openssl aes-256-cbc -salt -a -d -in foo.txt.enc -out foo.txt
```

## Asymmetric encryption

Asymmetric encryption uses private/public key. So first generate the private key and extract the public key.

```
openssl genrsa -aes256 -out private.key 8912
openssl rsa -in private.key -pubout -out public.key
```

Now wwe can use `rsautl`

to encrypt/decrypt:

```
openssl rsautl -encrypt -pubin -inkey public.key -in foo.txt -out foo.txt.enc
openssl rsautl -decrypt -inkey private.key -in foo.txt.enc -out foo.txt
```

But: Public-key crypto is not for encrypting arbitrarily long files (from a performance point of view). That's why we can't directly encrypt a large file using

`rsautl`

. Instead we use one-time random key.

### One-Time Random Key

- We use a symmetric cipher (here: AES) to do the normal encryption.
- Each time a new random symmetric key is generated, used for the normal encryption of the large file, and then encrypted with the RSA cipher (public key).
- The ciphertext together with the encrypted symmetric key is transferred to the recipient.
- The recipient decrypts the symmetric key using his private key.
- The recipient then uses the symmetric key to decrypt the large file.

The private key is never shared, only the public key is used to encrypt the random symmetric cipher.

Generate a symmetric key because you can encrypt large files with it

```
openssl rand -base64 32 > key.bin
```

Encrypt the large file using the symmetric key

```
openssl enc -aes-256-cbc -salt -in foo.txt -out foo.txt.enc -pass file:./key.bin
```

Encrypt the symmetric key so you can safely send it to the other person and destroy the un-encrypted symmetric key so nobody finds it

```
openssl rsautl -encrypt -inkey public.key -pubin -in key.bin -out key.bin.enc
shred -u key.bin
```

At this point, you send the encrypted symmetric key (`key.bin.enc`

) and
the encrypted large file (`foo.txt.enc`

) to the other person

The other person can then decrypt the symmetric key with their private key using

```
openssl rsautl -decrypt -inkey private.key -in key.bin.enc -out key.bin
```

Now they can use the symmetric key to decrypt the file

```
openssl enc -d -aes-256-cbc -in foot.txt.enc -out foo.txt -pass file:./key.bin
```

And you're done. The other person has the decrypted file and it was safely sent.