C语言实现AES加密解密

AES加密是美国联邦政府采用的一种块加密标准,如今已经被全世界广为使用。嵌入式开发中我们也经常会用到加密解密算法,如果没有硬件模块来实现,就需要用到C代码软件实现。下面介绍调用mbedTLS中的AES加密解密函数实现AES算法。

mbedTLS是一个开源TLS协议栈,主要用于嵌入式开发,其源代码网址为https://tls.mbed.org/aes-source-code。在该页面上点击downloadmbedTLS即可下载最新的协议栈,解压该压缩包就可以得到协议栈源代码。协议栈中的各种算法都独立封装在C文件中,彼此耦合度较低,目的是便于调用。我这里下的是2.2.1版本,解压后可以看到mbedtls-2.2.1\include\mbedtls路径下有许多header文件,将其添加到IDE的头文件中。在mbedtls-2.2.1\library下有许多c文件,我们只添加需要用到的aes.c

这里使用Visual Studio2013 C/C++环境进行编译演示。新建控制台应用,空工程。在Header Files文件夹下添加头文件,注意连文件夹一起添加,因为C文件中的include是包含路径的。然后把aes.c添加到source文件夹里。此时直接编译就能通过啦!

C语言实现AES加密解密_第1张图片




接下来就是在主函数里调用函数。这里调用了ECB模式和CBC模式两种。源代码如下:


#include
#include "mbedtls/aes.h"
#include "mbedtls/compat-1.3.h"

#define AES_ECB 0
#define AES_CBC 1
#define AES_CFB 2
#define AES_CTR 3
#define MODE AES_ECB

unsigned char key[16] = { 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22, 0x22 };
unsigned char plain[32] = { 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11, 0x11 };
unsigned char plain_decrypt[32] = { 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00 };
unsigned char IV[16];
unsigned char cypher[32];
int i = 0;
mbedtls_aes_context aes;



void SetIV()
{
	int i;
	for (i = 0; i < 16; i++)
	{ 
		IV[i] = 0x55;
	}
	
}
int main()
{
	
	
	
	if (MODE == AES_ECB)
	{
		    mbedtls_aes_setkey_enc(&aes, key, 128);//  set encrypt key			
			mbedtls_aes_crypt_ecb(&aes, AES_ENCRYPT, plain, cypher);
			mbedtls_aes_setkey_dec(&aes, key, 128);//  set decrypt key
			mbedtls_aes_crypt_ecb(&aes, AES_DECRYPT, cypher, plain_decrypt);
			i++;			
	}

	if (MODE == AES_CBC)
	{
		    mbedtls_aes_setkey_enc(&aes, key, 128);//  set encrypt key
			SetIV();
			mbedtls_aes_crypt_cbc(&aes, AES_ENCRYPT, 32, IV, plain, cypher);
			mbedtls_aes_setkey_dec(&aes, key, 128);//  set decrypt key
			SetIV();
			mbedtls_aes_crypt_cbc(&aes, AES_DECRYPT, 32, IV, cypher, plain_decrypt);
			i++;			
	}
}
单步运行,在 debug 窗口中可以观察到 cypher 数组的值改变,变为加密后的值,以及 plain _decrypt 数组中的值变为解密后的值,也就是和 plain 数组中一样。J~





你可能感兴趣的:(c语言,加密,library,加密)