原文链接: http://blog.csdn.net/yasi_xi/article/details/13997337
Openssl是很常见的C接口的库,个人觉得易用。以下是AES加密的使用备忘。如果你有一定的密码学基础,那么就很好理解。代码是从网上弄下来的(原始地址已经忘记了),然后在尝试的过程中改了一点东西。其它的cbc、cfb、ecb加密方式的用法都是类似的,只是函数名有点区别,就不一一列举了。
【yasi】IV: Initialization Vector,即初始化向量
一、接口简介
//设置加密密钥,使用字符缓冲区
int AES_set_encrypt_key(
const unsigned char *userKey,
const int bits,
AES_KEY *key);
//设置解密密钥,同样适用字符缓冲区
int AES_set_decrypt_key(
const unsigned char *userKey,
const int bits,
AES_KEY *key);
//加解密的接口,通过最后的enc来区分是加密还是解密操作
//每次执行AES_cbc_encrypt后,iv(向量)会被更新,
//所以需要自己保存它。
void AES_cbc_encrypt(
const unsigned char *in,
unsigned char *out,
const unsigned long length,
const AES_KEY *key,
unsigned char *ivec,
const int enc);
二、一个简单的Makefile
【yasi】针对CentOS环境,做了修改
LNK_OPT = -g -L/usr/lib64/ -lssl
all:
rm -f codec
g++ -g aes_codec.cpp -o codec $(LNK_OPT)
clean:
rm -f codec
三、示例代码
【yasi】对源链接的代码做了点修改:随机明码 改 静态明码
#include
#include
#include
#include
/* file testaes.cpp */
static void hexdump(
FILE *f,
const char *title,
const unsigned char *s,
int l)
{
int n = 0;
fprintf(f, "%s", title);
for (; n
if ((n % 16) == 0) {
fprintf(f, "\n%04x", n);
}
fprintf(f, " %02x", s[n]);
}
fprintf(f, "\n");
}
int main(int argc, char **argv)
{
//128bits key.
unsigned char rkey[16];
//Internal key.
AES_KEY key;
//Testdata.
// [yasi] Make static content instead of random text
unsigned char plaintext[AES_BLOCK_SIZE * 4] =
{
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'i',
'0', '1', '2', '3', '4', '5', '6', '7', '0', '1', '2', '3', '4', '5', '6', '7',
'a', 'b', 'c', 'd', 'e', 'f', 'g', 'i', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'i',
'0', '1', '2', '3', '4', '5', '6', '7', '0', '1', '2', '3', '4', '5', '6', '7'
};
unsigned char ciphertext[AES_BLOCK_SIZE * 4];
unsigned char checktext[AES_BLOCK_SIZE * 4];
//Init vector.
unsigned char iv[AES_BLOCK_SIZE * 4];
//Save vector.
unsigned char saved_iv[AES_BLOCK_SIZE * 4];
int nr_of_bits = 0;
int nr_of_bytes = 0;
//Zeror buffer.
memset(ciphertext, 0, sizeof ciphertext);
memset(checktext, 0, sizeof checktext);
//Generate random
RAND_pseudo_bytes(rkey, sizeof rkey);
RAND_pseudo_bytes(saved_iv, sizeof saved_iv);
hexdump(stdout, "