本人尝试编写的测试利用openssl库函数进行AES中cbc的加解密,至于其它ecb,cfb,ofb等的加解密可套路以下程序。
在贴代码之前本人需要分享三个网站,个人认为对理解AES加解密和text的编写极有用处
http://www.cnblogs.com/adylee/archive/2007/09/14/893438.html
http://www.open-open.com/lib/view/open1385946495658.html
http://blog.csdn.net/qncj666/article/details/8244893
#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <errno.h>
#include <stdlib.h>
#include <unistd.h>
#include <openssl/aes.h>
int main()
{
char Source[100];
unsigned char *InputData = NULL;
unsigned char *EncryptData = NULL;
unsigned char *DecryptData = NULL;
unsigned char ivec[AES_BLOCK_SIZE];
unsigned char key[AES_BLOCK_SIZE];
AES_KEY AesKey;
strcpy(Source, "1234567890abcde");//the data which need to be encrypted
int SetDataLen = strlen(Source)+1;
int DataLen = strlen(Source);
printf("%d\n",SetDataLen);
//generate own AES key
for(int iloop = 0;iloop < 16; iloop++)
{
key[iloop] = 32 + iloop;
}
InputData = (unsigned char *)calloc(SetDataLen+1, sizeof(char)); //distribute the place to put datas
memcpy(InputData, Source, DataLen); //put source into inputdata
EncryptData = (unsigned char *)calloc(SetDataLen+1, sizeof(char));
DecryptData = (unsigned char *)calloc(SetDataLen+1, sizeof(char));
//set encryption key
if(AES_set_encrypt_key(key,128,&AesKey)<0)
{
printf("Unable to set encryption key in AES...\n");
}
for(int i=0;i<AES_BLOCK_SIZE; i++)
{
ivec[i] = 0; //ivec is like the first IV in the picture
}
for(int i = 0; i<16; i++)
{
printf("%02x ",InputData[i]); //for text the data in the Inputdata
}
printf("\n");
//encryption
AES_cbc_encrypt(InputData,EncryptData,SetDataLen,&AesKey,ivec,AES_ENCRYPT);
for(int i=0; i<16; i++)
{
printf("%02X ", *(EncryptData+i)); //put out the number of encryptdata in hex formats
}
printf("\n");
// set decryption key
if(AES_set_decrypt_key(key,128,&AesKey)<0) //AES_set_decrypt_key is to get the AesKey
{
printf("Unable to set encryption key in AES...\n");
}
for(int i=0;i<AES_BLOCK_SIZE; i++)
{
ivec[i] = 0; //the ivec to decryption should be same with encryption
}
//decryption
AES_cbc_encrypt(EncryptData, DecryptData,SetDataLen,&AesKey,ivec,AES_DECRYPT);
for(int i=0; i<16; i++)
{
printf("%02X ", DecryptData[i]); //put out the number of decryptdata in hex formats
}
printf("\n");
//printf("DecryptData:%s...\n", (char *)DecryptData);
return 0;
}