openssl AES加密例子

openssl

OpenSSL 是一个安全套接字层密码库,囊括主要的密码算法、常用的密钥和证书封装管理功能及SSL协议,并提供丰富的应用程序供测试或其它目的使用。

首先,要安装 openssl:

centos命令:

sudo yum install openssl-devel

ubuntu命令:

sudo apt-get install libssl-dev

//========================================================================

//========================================================================

include <stdio.h>

include <stdlib.h>

include <string.h>

include <memory.h>

include <openssl/aes.h>

include <openssl/evp.h>

include <openssl/rsa.h>

void HexCode(unsigned char* data, int len)
{
int i = 0;
for(; i < len; i++)
printf("%02x", (unsigned int)data[i]);
printf("\n");
}

int main(void)
{
const int len = 3;
//AES 块到长度,是16个字节;
printf("AES_BLOCK_SIZE = %d\n", AES_BLOCK_SIZE);

char userkey[AES_BLOCK_SIZE] = {0};
unsigned char *data = malloc(AES_BLOCK_SIZE*len);
unsigned char *cipher = malloc(AES_BLOCK_SIZE*len);
unsigned char *plain = malloc(AES_BLOCK_SIZE*len);

int i;
AES_KEY key = {0};

memset((void*)userkey, 0, AES_BLOCK_SIZE);
memset((void*)data, 0, AES_BLOCK_SIZE*len);
memset((void*)cipher, 0, AES_BLOCK_SIZE*len);
memset((void*)plain, 0, AES_BLOCK_SIZE*len);

strcpy(userkey, "0123456789abcde");
strcpy(data, "##@@!!!ABC123");

printf("原始数据:\n");

HexCode(data, AES_BLOCK_SIZE*len);

//set key;
printf("set aes key = %s\n", userkey);
AES_set_encrypt_key(userkey, 128, &key);    //设置加密的秘钥;
//执行加密;
for(i = 0; i < len; i++)
{
    AES_ecb_encrypt(data+i*AES_BLOCK_SIZE, cipher+i*AES_BLOCK_SIZE, &key, AES_ENCRYPT);
}

printf("加密数据:\n");
HexCode(cipher, AES_BLOCK_SIZE*len);

//set key to uncode
AES_set_decrypt_key(userkey, 128, &key);    //设置解密的秘钥
//执行解密;
for(i = 0; i < len; i++)
{
    AES_ecb_encrypt(cipher+i*AES_BLOCK_SIZE, plain+i*AES_BLOCK_SIZE, &key, AES_DECRYPT);
}
printf("揭密数据:\n");

HexCode(plain, AES_BLOCK_SIZE*len);

printf("uncode aes = %s\n", plain);

free(data);
free(cipher);
free(plain);

return 0;

}

编译:

! /bin/sh

out=exe

rm $out

gcc test.c -o $out -lcrypto

运行:

[hill@Ubunut10 aes]./make.sh [hill@Ubunut10 aes]./exe
AES_BLOCK_SIZE = 16
原始数据:
232340402121214142433132330000000000000000000000000000000000000000000000000000000000000000000000
set aes key = 0123456789abcde
加密数据:
1f84ced9ca24eafed2cf4709b2324578b7a085b9b36333a3a667929584c40c1bb7a085b9b36333a3a667929584c40c1b
揭密数据:
232340402121214142433132330000000000000000000000000000000000000000000000000000000000000000000000
uncode aes = ##@@!!!ABC123
[hill@Ubunut10 aes]$
韦凯峰Linux编程学堂,一瓶啤酒的价格,视频+文档,零基础入门,掌握Linux C/C++编程,Linux系统编程,用技术改变生活,改变自己,改变世界!

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容