So, lets look at how CBC works first. The following picture shows the encryption when using CBC (in this case, using AES as the cipher).算法
Basically, Cipher-Block-Chaining means that previous to putting the cleartext data block into the cipher itself (AES, DES, Triple-DES, …) it is XORed with the previous cipher block. This works fine for all but the first cleartext block, as – of course – there is no previous cipher block. So, the encrypting entity chooses a random value of block size (8bytes for DES, 16bytes for AES) to use in the first XOR. This value is the so-called Initialization Vector or IV. The following picture depicts the decryption using CBC.oracle
Basically, the decryption works very similarily to encryption. This time, the ciphertext block is put through the decryption routine and is then XORed with the previous ciphertext block. Also, for the first block, we use the IV again. The important thing to understand at this point is the following. If, for some reason, we can deduce what comes out of the AES block in the first cipher (what is denoted here as the Intermediary Message (IM)), we can produce any 「plain text」 we want. Why can we do that? Well, CBC uses the IV to XOR the IM and we usually control this. So, for each byte of message we want to 「generate」, we choose the IV as follows:app
IV[n] = IM[n] ^ DesiredMessage[n]
If you wonder how you might deduce the IM, look up 「padding oracles」 on Google.dom
As both DES and AES are block ciphers, the length of the given input must always be a multiple of the block size. As messages might not fit this condition, the plaintext is padded to a multiple of block size. However, the decrypting entity must somehow know, how much padding was append to the original cleartext. There a multiple ways of doing this, we will focus on PKCS5 as it was needed in this challenge.ide
PKCS5 encodes a padding of n bytes by filling the all of the padded 「slots」 with n. Basically, if we have only one byte padding, the last byte will be 1. If we have e.g. 5 bytes padding, the last 5 bytes will all be set to 5. Please note, that padding must always be provided. Thus, if the message actually had a length which was a multiple of the block size, there will be exactly one block added to the message. For 8byte ciphers like DES, we then have a block of length 8b filled completely with 8s.this
CBC加解密原理以下圖所示, 圖片來源維基百科加密
CBC加密原理:明文跟向量異或,再用KEY進行加密,結果做爲下個BLOCK的初始化向量。解密原理:使用密鑰先對密文解密,解密後再同初始向量異或獲得明文。code
CBC須要對明文塊大小進行Padding(補位),因爲先後加密的相關性,只能實施串行化動做,沒法並行運算。另外,CBC須要參量:密鑰和初始化向量。blog
CTR加密原理:用密鑰對輸入的計數器加密,而後同明文異或獲得密文。解密原理:用密鑰對輸入計數器加密,而後同密文異或獲得明文。圖片
CTR不須要Padding,並且採用了流密鑰方式加解密,適合於並行運算,CTR涉及參量:Nounce隨機數、Counter計數器和密鑰。Nounce隨機數和Counter計數器總體可看做計數器,由於只要算法約定好,就能夠迴避掉串行化運算。
參考資料: