CTR Mode is a stream cipher that generates a key stream by encrypting successive accumulated counters, and in CTR mode, each packet corresponds to a successive cumulative counter, and the key stream is generated by encrypting the counter. The final cipher packet is obtained by XOR the bit sequence encrypted by the counter and the plaintext packet, as shown in:
The method for generating the counter is as follows:
The CTR mode, like the OFB mode, belongs to the stream password. If we take out the encryption process for a single packet, then the difference between the OFB mode and the CTR mode is easy to understand:
CTR-Mode Encryption:
#include <string. H>#defineInch#defineOut//Suppose that the encryption is grouped into a group of 4 bytes/*************************************************************************** function: Encryption algorithm (with key XOR) * Parameter: Lpszdata Current plaintext Packet data * Lpszkey Key * Lpszdedata Encrypted result * * return value: ******************************* *******************************************/voidEncrypt (inConst Char*lpszdata, inConst Char*lpszkey, outChar*lpszendata) { inti =0; for(i =0; I <4; i++) {Lpszendata[i]= Lpszdata[i] ^Lpszkey[i]; }}/*************************************************************************** function: Current plaintext and current key stream xor * parameter: Lpszdata Current plaintext Packet data * Lpszkeystream current cipher algorithm output * Lpszxordata save XOR Data * * return value: **************************** **********************************************/voidXordata (inConst Char*lpszdata, inConst Char*lpszkeystream, outChar*lpszxordata) { inti =0; for(i =0; I <4; i++) {Lpszxordata[i]= Lpszdata[i] ^Lpszkeystream[i]; }}intMainintargcChar*argv[]) { CharSzdata[] ="Hello world!"; Charszendata[ -] = {0}; Charszdedata[ -] = {0}; Char*lpszkey ="1234"; inti =0; CharSzctr[] = {0x39,0x39,0x39,0x01};//Suppose the last byte is a counter Charszctrendata[8] = {0}; printf ("Original data:%s\r\n", Szdata); while(true) { if(strlen (szdata + i) = =0) { Break; } //Current counter and encryption algorithm encryptionEncrypt (szctr, Lpszkey, Szctrendata); //Clear text grouping is different or manipulated with the above encrypted valueXordata (Szdata + i, szctrendata, Szendata +i); //Update the value of the current counterszctr[3] +=1; I+=4; } printf ("post-encrypted data:%s\r\n", Szendata); CharSztmp[] = {0x39,0x39,0x39,0x01}; memcpy (szctr, sztmp,4); I=0; while(true) { if(strlen (szendata + i) = =0) { Break; } //Current counter and encryption algorithm encryptionEncrypt (szctr, Lpszkey, Szctrendata); //ciphertext grouping and the above encrypted value to do different or operationXordata (Szendata + i, szctrendata, Szdedata +i); //Update the value of the current counterszctr[3] +=1; I+=4; } printf ("post-decryption data:%s\r\n", Szdedata); return 0;}
Raw data: Hello world!
Post-encrypted data: @nfYg +]YZGN
Decrypted data: Hello world!
.
Block cipher Mode: CTR Mode (counter mode)