Skip to main content

加密檔案 - OpenSSL

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

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 (對稱式加密)
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:

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 (對稱式加密)
# 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:

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

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

Hashing
# For file
openssl dgst -sha256 my.file

# For string
echo "HelloWorld" | openssl sha256

 

參考網站