openssl之aes对称加密
AES:密码学中的高级加密标准(Advanced Encryption Standard,AES),又称 Rijndael加密法。
对称加密:用同一个密码 加密/解密 文件。
使用openssl中的两函数加密解密 (默认只能加密16字节)
AES_set_encrypt_key(unsigned char*)key, int, &AES_KEY) -- 加密密钥
AES_set_decrypt_key(unsigned char*)key, int, &AES_KEY) -- 解密密钥
AES_cbc_encrypt(unsigned char*)str_in, (unsigned char*)out, int len, &AES_KE Y, unsigned char*, AES_DECRYPT)
#include "openssl/aes.h" unsigned char key[AES_BLOCK_SIZE]; unsigned char iv[AES_BLOCK_SIZE]; #define AES_BITS 10240 #define MSG_LEN 10240 /********************************************************** 函数名:getlen 参数:char *result --字符串地址 返回值:int --字符串长度 说明: --获取字符串长度 ***********************************************************/ int getlen(char *result){ int i = 0; while (result[i] != '\0'){ i++; } return i; }
加密:
/********************************************************** 函数名:aes_encrypt 参数:const char* str_in --输入字符 参数:unsigned char* key --key 参数:unsigned char* out --输出字符 返回值:int --0失败 1成功 说明:加密 ***********************************************************/ int aes_encrypt(char* str_in, char* key, char* out) { if (!str_in || !key || !out) return 0; //加密的初始化向量 unsigned char iv[AES_BLOCK_SIZE]; //16位密码 char tmpIV[] = "0123456789abcdef"; for (int i = 0; i < 16; ++i) iv[i] = tmpIV[i]; AES_KEY aes; if (AES_set_encrypt_key((unsigned char*)key, 128, &aes) < 0) { return 0; } int len = getlen(str_in); AES_cbc_encrypt((unsigned char*)str_in, (unsigned char*)out, len, &aes, iv, AES_ENCRYPT); return 1; }
解密:
/********************************************************** 函数名:aes_decrypt 参数:const char* str_in --输入 参数:unsigned char* key --key 参数:unsigned char* out --输出 返回值:int --0失败 1成功 说明: --解密 ***********************************************************/ int aes_decrypt(char* str_in, char* key, char* out) { if (!str_in || !key || !out) return 0; unsigned char iv[AES_BLOCK_SIZE];//加密的初始化向量 char tmpIV[] = "0123456789abcdef"; for (int i = 0; i < 16; ++i) iv[i] = tmpIV[i];
AES_KEY aes; if (AES_set_decrypt_key((unsigned char*)key, 128, &aes) < 0) { return 0; } int len = getlen(str_in); AES_cbc_encrypt((unsigned char*)str_in, (unsigned char*)out, len, &aes, iv, AES_DECRYPT); return 1; }
问题:每次只能加密16个字节
查看源码: