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计数器总体可看做计数器,由于只要算法约定好,就能够回避掉串行化运算。
参考资料: