[Encrypt] 區塊加密解密指南(對稱式) – Block Cipher guide

Intro

一般所謂的對稱金鑰演算法,以區塊加密演算法為主,演算法如AES或DES。

區塊加密工作模式:所謂的Mode,如ECBCBCPCBCCFBOFBCTR。延伸出初始向量(IV)

ECB,CBC,OFB,CFB,CTR和XTS模式僅僅提供了機密性;為了保證加密資訊沒有被意外修改或惡意篡改,需要採用分離的訊息驗證碼,例如CBC-MAC。

認證加密模式(AE,Authenticated Encryption),或稱為authenc,結合了加密和認證的單一模式。AE模式的例子包括CCM,GCM,CWC,EAX,IAPM和OCB。


Mode - 工作模式

最簡單的加密模式為ECB:每個加密塊獨立加密,不須使用IV (亦即相同內文,密文相同)

經典常用的加密模式為CBC:每個明文塊先與前一個密文塊進行互斥或後,再進行加密。在這種方法中,每個密文塊都依賴於它前面的所有明文塊。同時,為了保證每條訊息的唯一性,在第一個塊中需要使用IV

Encryption
Decryption


IV - 初始向量

初始向量(Initialization vector)


Padding - 填充

填充(Padding)

部分模式(即ECB和CBC)因塊密碼只能對確定長度的資料塊進行處理,需要最後一塊在加密前進行填充。
CFB,OFB和CTR模式不需要對長度不為密碼塊大小整數倍的訊息進行特別的處理。


實作

OpenSSL指令

// Encrypt with EBC
$ openssl enc -aes-256-ecb -in plaintext.txt -out encrypted.txt -k YourSecretKey

// Decrypt with EBC
$ openssl enc -d -aes-256-ecb -in encrypted.txt -out decrypted.txt -k YourSecretKey
// Encrypt with CBC (auto IV)
$ openssl enc -aes-256-cbc -in plaintext.txt -out encrypted.txt -k YourSecretKey

// Decrypt with CBC (auto IV from chipherText)
$ openssl enc -d -aes-256-cbc -in encrypted.txt -out decrypted.txt -k YourSecretKey

// Encrypt with CBC (IV in hex format)
$ openssl enc -aes-256-cbc -in plaintext.txt -out encrypted.txt -k YourSecretKey -iv 00112233445566778899aabbccddeeff

// Decrypt with CBC (IV in hex format)
openssl enc -d -aes-256-cbc -in encrypted.txt -out decrypted.txt -k YourSecretKey -iv 00112233445566778899aabbccddeeff

Key 參數 -k <password> 省略的話會用對話模式要求輸入Key。

需要 IV 的演算法,加密時若沒有指定 IV 則自動產生的 IV 會加到密文 prefix

Leave a Reply

Your email address will not be published. Required fields are marked *