# OpenSSL

Create Example Reference File, let us create a 1GB large text file using the fallocate command:

```shell
fallocate -l 1024M test.txt
echo "LinuxShellTips tutorial on encrypting a large file with OpenSSL in Linux" >> test.txt
cat test.txt
```

##### Encrypt File with Password (對稱式加密)  


```shell
openssl enc -aes-256-cbc -pbkdf2 -p -in test.txt -out test.txt.enc
```

- enc executes the symmetric key encryption process.
- -aes-256-cbc specifies the use of 256 bits cryptographic key.
- -pbkdf2 is the default algorithm being used.
- -p prints used salt, key, and IV.
- -in points to the input file.
- -out points to the output file.

To decrypt the file, run:

```shell
openssl aes-256-cbc -d -pbkdf2 -in test.txt.enc -out sample_decrypted.txt
```

> You will be required to enter the encryption password you generated earlier.

##### Encrypt File with Key (對稱式加密)  


```shell
# generate a key file
openssl rand 256 > symmetric_keyfile.key
# use the keyfile to encrypt our file
openssl enc -in test.txt -out test.txt.enc -e -aes-256-cbc -pbkdf2 -k symmetric_keyfile.key
```

To decrypt the file, run:

```shell
openssl enc -in test.txt.enc -out draft_decrypted.txt -d -aes-256-cbc -pbkdf2 -k symmetric_keyfile.key
```

##### 非對稱式加密 (Asymmetric Encryption)

使用非對稱式加密對一個大檔案進行加密，可能遇到錯誤: data too large for key size.

[![data-too-large-for-key-size.png](https://osslab.tw/uploads/images/gallery/2022-07/scaled-1680-/data-too-large-for-key-size.png)](https://osslab.tw/uploads/images/gallery/2022-07/data-too-large-for-key-size.png)

> TIP: 非對稱加密又稱公鑰加密。在使用前要準備好一對私鑰與公鑰，使用公鑰進行檔案的加密，解密時則使用私鑰，操作上較複雜，但是安全性較佳。

##### Hashing

檔案校驗

```bash
# For file
openssl dgst -sha256 my.file

# For string
echo -n "HelloWorld" | openssl dgst -sha256
```

##### Generate a token key

```bash
openssl rand -hex 32
```

##### 參考網站  


- [OpenSSL 對稱式、非對稱式加密檔案指令教學與範例](https://officeguide.cc/linux-openssl-file-symmetic-asymmetric-encryption-commands-tutorial-examples/)