openssl cipher算法接口使用示例:
//gcc -g -lssl cipher_test.c -lcrypto -L /usr/local/lib/
#include <string.h>
#include <openssl/evp.h>
#define IV_SIZE 8
#define KEY_SIZE 24
#define INPUT_SIZE 100
void print_hexdata(unsigned char *b, int len, char *title)
{
int i = 0, c = 0;
printf("===================================== %s =====================================\n", title);
for (; i<len; i++) {
printf("0x%02x ", b[i]);
c++;
if (!(c%16))
printf("\n");
}
printf("\n");
}
int main()
{
const EVP_CIPHER *cipher;
EVP_CIPHER_CTX *ctx;
ctx = EVP_CIPHER_CTX_new();
unsigned char key[KEY_SIZE],iv[IV_SIZE],input[INPUT_SIZE],en_output[INPUT_SIZE],de_output[INPUT_SIZE];
int input_size = INPUT_SIZE, en_output_size, de_output_size;
int i = 0, ret = 0;
for(i=0;i<KEY_SIZE;i++)
{
memset(&key[i],i,1);
}
for(i=0;i<IV_SIZE;i++)
{
memset(&iv[i],i,1);
}
for(i=0;i<INPUT_SIZE;i++)
{
memset(&input[i],i,1);
}
cipher=EVP_des_ede3_ofb();
//加密
EVP_CIPHER_CTX_init(ctx);
ret=EVP_EncryptInit_ex(ctx,cipher,NULL,key,iv);
if(ret!=1)
{
printf("EVP_EncryptInit_ex err1!\n");
return -1;
}
EVP_EncryptUpdate(ctx,en_output,&en_output_size,input,INPUT_SIZE);
EVP_CIPHER_CTX_cleanup(ctx);
// 解密
EVP_CIPHER_CTX_init(ctx);
ret=EVP_DecryptInit_ex(ctx,cipher,NULL,key,iv);
if(ret!=1)
{
printf("EVP_DecryptInit_ex err1!\n");
return -1;
}
EVP_DecryptUpdate(ctx,de_output,&de_output_size,en_output,en_output_size);
EVP_CIPHER_CTX_cleanup(ctx);
if((input_size != de_output_size) || (memcmp(de_output,input,input_size)))
{
printf("err!\n");
return -1;
}
print_hexdata(input, input_size, "input");
print_hexdata(en_output, en_output_size, "en_output");
print_hexdata(de_output, de_output_size, "de_output");
printf("test ok\n");
return 0;
}
执行结果: