Keep on going, never give up.

AES CBC和CTR加解密实例

AES(Advanced Encryption Standard,高级加密标准)又叫Rijndael加密法,用来替代DES算法。常见AES加密模式有ECB、CBC、CFB、OFB和CTR等五种, CFB、OFB都带反馈,做流加密用的多,CBC和CTR、ECB多用于独立block加密,由于ECB算法有点小缺点(相同输入,相同输出,容易明文攻击),所以CBC和CTR这两种加解密方式用的较多,也是很多标准规范要求的实现算法,下面看一下这两种算法原理。

AES跟Rijndael相比有点小区别,就是使用固定块(block size)为128bits(16字节)(原Rijndael块大小更灵活),密钥长度支持128、192或256位。

 

一、AES CBC加解密原理

CBC加解密原理如下图所示(图片来源维基百科,参考文末地址):

CBC加密原理:明文跟向量异或,再用KEY进行加密,结果作为下个BLOCK的初始化向量。解密原理:使用密钥先对密文解密,解密后再同初始向量异或得到明文。

CBC需要对明文块大小进行Padding(补位),由于前后加密的相关性,只能实施串行化动作,无法并行运算。另外,CBC需要参量:密钥和初始化向量。

二、AES CTR加解密原理

 

CTR加密原理:用密钥对输入的计数器加密,然后同明文异或得到密文。解密原理:用密钥对输入计数器加密,然后同密文异或得到明文。

CTR不需要Padding,而且采用了流密钥方式加解密,适合于并行运算,CTR涉及参量:Nounce随机数、Counter计数器和密钥。Nounce随机数和Counter计数器整体可看作计数器,因为只要算法约定好,就可以回避掉串行化运算。

三、AES CBC和CTR加解密实例

下文实例使用了第三方开源源码,官方网址:http://www.gladman.me.uk/, 本文测试源码来源:http://gladman.plushost.co.uk/oldsite/AES/index.php,测试时,如下源码文件需加入工程:aes_modes.c、aescrypt.c、aeskey.c、aestab.c。

测试源码如下:

#include <iostream>
#include <string>
#include <time.h>

#include "aes/aes.h"

typedef unsigned char  uint8;
typedef char           int8;
typedef unsigned short uint16;
typedef short          int16;
typedef unsigned int   uint32;
typedef int            int32;

typedef unsigned __int64 uint64;
typedef __int64          int64;
/******************************
For _LINUX
typedef long   long    int64;
typedef unsigned long  long  uint64;
******************************/

using namespace std;

//same as function rfc3686_inc
void ctr_inc(unsigned char ctr_buf[16])
{
    if(!(++(ctr_buf[15])))
        if(!(++(ctr_buf[14])))
            if(!(++(ctr_buf[13])))
                ++(ctr_buf[12]);
}

//same as function rfc3686_init
//4Bytes nounce+8Bytes iv+4Bytes counter
void ctr_init( unsigned char nonce[4], unsigned char iv[8], unsigned char ctr_buf[16])
{
    memcpy(ctr_buf, nonce, 4);
    memcpy(ctr_buf +  4, iv, 8);
    memset(ctr_buf + 12, 0, 4); 
    ctr_inc(ctr_buf);
}

void print_hex(uint8* buf, uint64 len) {
	//Print results:
	for(int i=0;i<len;i++) {
		printf("%02X",buf[i]);
		if(15 == i%16)
			printf("\n");
	}
	printf("\n");
}

void main() {
	
	uint8	key[]	= {0x10,0xa5,0x88,0x69,0xd7,0x4b,0xe5,0xa3,0x74,0xcf,	0x86,0x7c,0xfb,0x47,0x38,0x59};//AES::DEFAULT_KEYLENGTH
	uint8	buf[16];//tmp buffer

	uint8	msg[]	= "HelloWorld!23456";
	uint64	fsize=strlen((char*)msg);//message size
	uint8*	DataBuf=new uint8[1024];//Data Buffer


	//AES with CBC
	printf("AES with CBC\n");			
	
	//Copy data
	memset(DataBuf,0,1024);
	strcpy((char*)DataBuf,(char*)msg);
	uint8* pDataBuf = DataBuf;//tmp pointer
	uint8	iv1[]	= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,	0x00,0x00,0x00,0x00,0x00,0x00};

	uint64	iEncryptTimes = fsize/16+1;
	uint8	iPaddings	  = 16-fsize%16;//Padding size
	uint64	newlen = fsize+iPaddings;//New length
	
	//memcpy(DataBuf,iv,16);//Save iv
	memset(pDataBuf+fsize, iPaddings,iPaddings);//Padding
	printf("input	=\n");
	print_hex(DataBuf,newlen);
	aes_encrypt_ctx en_ctx[1];//Init encrypt
	
	//Encrypt
	for(uint64 i=0;i<iEncryptTimes;i++) {
		aes_encrypt_key128(key,en_ctx);
		aes_cbc_encrypt(pDataBuf,buf,16,iv1,en_ctx);//iv has been changed, ctx has been changed!!!
		memcpy(pDataBuf,buf,16);
		pDataBuf += 16;
	}
	
	printf("encrypt	=\n");
	print_hex(DataBuf,newlen);
	
	//Decrypt
	pDataBuf = DataBuf;
	uint8	iv2[]		= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,	0x00,0x00,0x00,0x00,0x00,0x00};
	uint8	buf3[256]={'\0'};
	aes_decrypt_ctx de_ctx[1];
	aes_decrypt_key128(key,de_ctx);
	aes_cbc_decrypt(pDataBuf,buf3,newlen,iv2,de_ctx);
	
	printf("decrypt	=\n");
	print_hex(buf3,newlen);
	
	//================================

	printf("AES with CTR\n");			
	//Copy data
	memset(DataBuf,0,1024);
	strcpy((char*)DataBuf,(char*)msg);
	pDataBuf = DataBuf;//tmp pointer
	uint8	iv3[]	= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,	0x00,0x00,0x00,0x00,0x00,0x00};

	iEncryptTimes = fsize/16;
	uint8	iRemain		  = fsize%16;
	uint8	ctr_buf[AES_BLOCK_SIZE];
	
	//Save iv(as ctrl buffer)
	//memcpy(DataBuf,iv,16);
	printf("input	=\n");
	print_hex(DataBuf,fsize);
	
	//Init encrypt
	//aes_encrypt_ctx en_ctx[1];
	
	//Encrypt
	for(i=0;i<iEncryptTimes;i++) {
		aes_encrypt_key128(key,en_ctx);
		ctr_init(iv3,iv3+4,ctr_buf);//we set iv as the nouce
		aes_ctr_encrypt(pDataBuf,buf,16,ctr_buf,ctr_inc,en_ctx);//iv has been changed, ctx has been changed!!!
		memcpy(pDataBuf,buf,16);
		pDataBuf += 16;
	}
	
	if(iRemain!=0) {//last times
		pDataBuf += i*16;
		aes_encrypt_key128(key,en_ctx);
		ctr_init(iv3,iv3+4,ctr_buf);//we set iv as the nouce
		aes_ctr_encrypt(pDataBuf,buf,iRemain,ctr_buf,ctr_inc,en_ctx);//iv has been changed, ctx has been changed!!!
		memcpy(pDataBuf,buf,iRemain);
	}
	
	printf("encrypt	=\n");
	print_hex(DataBuf,fsize);
	
	//Decrypt
	pDataBuf = DataBuf;
	uint8	iv4[]		= {0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,0x00,	0x00,0x00,0x00,0x00,0x00,0x00};
	//uint8	buf3[256]={'\0'};
	//aes_decrypt_ctx de_ctx[1];
	//aes_decrypt_key128(key,de_ctx);
	aes_encrypt_key128(key,en_ctx);
	ctr_init(iv4,iv4+4,ctr_buf);//we set iv as the nouce
	aes_ctr_decrypt(pDataBuf,buf3,16,ctr_buf,ctr_inc,en_ctx);
	printf("decrypt	=\n");
	print_hex(buf3,fsize);
	
	printf("\n");
}

输出如下(CBC未去掉Padding):

  • AES with CBC
  • input   =
  • 48656C6C6F576F726C64213233343536
  • 10101010101010101010101010101010
  • encrypt =
  • F928E09884AA2BA8CC4B73C09304250C
  • C9A0EEFF2295B5D83BEA0410001BD7C6
  • decrypt =
  • 48656C6C6F576F726C64213233343536
  • 10101010101010101010101010101010
  •  
  • AES with CTR
  • input   =
  • 48656C6C6F576F726C64213233343536
  • encrypt =
  • 1CA0978FE499969C769B6346D46B66F9
  • decrypt =
  • 48656C6C6F576F726C64213233343536

参考资料:

http://zh.wikipedia.org/wiki/高级加密标准

http://zh.wikipedia.org/zh/块密码的工作模式

如您对AES/DEX加密解密有兴趣,建议阅读:Java DES加密和解密Java AES加密和解密两篇文章。

相关评论(0):  

发表评论:

◎欢迎参与讨论,请在这里发表您的看法、交流您的观点。

订阅博客

最新文章

本站采用创作共用版权协议, 要求署名、非商业用途和保持一致. 转载也必须遵循“署名-非商业用途-保持一致”的创作共用协议. 返回顶部
Copyright@2005-2016 Metsky.com, All rights Reserved.