红联Linux门户
Linux帮助

Linux下使用openssl的AES加密-ECB模式

发布时间:2017-04-14 09:20:45来源:blog.csdn.net/liuyueyi1995作者:liuyueyi1995
最近需要用到AES加密,为了图方便就打算使用openssl自带的AES加密算法的API来实现。
主要用到了ECB和CBC两种加密模式。
 
ECB模式如下:
 
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <openssl/aes.h>
int main(int argc, char**argv) {
if(argc != 2) {
printf("使用方法为:\n./ecb text\ntext为待加密的明文。\n");
return -1;
}
unsigned char *data = argv[1]; //接收参数
printf("原始数据:%s\n",data);
int length = ((strlen(data)+AES_BLOCK_SIZE-1)/AES_BLOCK_SIZE)*AES_BLOCK_SIZE;  //对齐分组
char userkey[AES_BLOCK_SIZE];
unsigned char *encrypt_result = malloc(length);
unsigned char *decrypt_result = malloc(length);
AES_KEY key;
memset((void*)userkey,'k',AES_BLOCK_SIZE);
memset((void*)encrypt_result, 0, length);
memset((void*)decrypt_result, 0, length);
AES_set_encrypt_key(userkey, AES_BLOCK_SIZE*8, &en_key);
printf("加密密钥:%d\n",en_key);
int len = 0;
/*循环加密,每次只能加密AES_BLOCK_SIZE长度的数据*/
while(len < length) {
AES_encrypt(data+len, encrypt_result+len, &en_key);
len += AES_BLOCK_SIZE;
}
printf("加密结果:%s\n",encrypt_result);
AES_set_decrypt_key(userkey, AES_BLOCK_SIZE*8, &de_key);
printf("解密密钥:%d\n",de_key);
len = 0;
/*循环解密*/
while(len < length) {
AES_decrypt(encrypt_result+len, decrypt_result+len, &de_key);
len += AES_BLOCK_SIZE;
}
printf("解密结果:%s\n",decrypt_result);
}
 
本文永久更新地址:http://www.linuxdiyf.com/linux/29980.html