您的位置:首页 > 运维架构

使用openssl中的EVP通用加密算法接口的之--解密测试例子

2014-01-22 16:56 666 查看
/*********************************************************************

* Author : Samson

* Date : 01/22/2014

* Test platform:

* 3.6.10-4.fc18.i686.PAE

* GNU bash, version 4.2.39

* *******************************************************************/

此测试例子是使用的openssl库中提供的EVP系列函数对数据进行解密的一个测试,选择的算法为:AES128,加密模式为:CBC,此解密算法模式下需要的参数为:16字节的解密key,16字节的IV(初始化向量),数据的长度根据需要对宏DATA_LEN进行修改。若是要选择其它的算法,请自己man一下相关的函数接口是否存在。例如要使用的算法为AES192 CBC的算法的话,那么在下面加红的那句中把
rv = EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(),NULL, key, iv); 中的EVP_aes_128_cbc修改为EVP_aes_192_cbc,但是对应的参数也要进行相应长度的值的输入,EVP_aes_192_cbc算法的加密key的长度应该为24字节,IV的长度还是16字节,这个具体算法要根据具体算法进行参数的输入,进行举一反三。

#include <stdio.h>

#include <string.h>

#include <errno.h>

#include <resolv.h>

#include <stdlib.h>

#include <unistd.h>

#include <openssl/ssl.h>

#include <openssl/err.h>

#include <openssl/evp.h>

#include <openssl/x509.h>

#define DATA_LEN 32

#define EVP_MAX_KEY_LENGHT 64

int main()

{

EVP_CIPHER_CTX ctx;

unsigned char key[EVP_MAX_KEY_LENGHT] = "\x00\x01\x02\x03\x04\x05\x06\x07\x08\x09\x0a\x0b\x0c\x0d\x0e\x0f";

unsigned char iv[EVP_MAX_KEY_LENGHT] = "\xc2\x86\x69\x6d\x88\x7c\x9a\xa0\x61\x1b\xbb\x3e\x20\x25\xa4\x5a";

unsigned char out[1024] = {0};

int outl, tmp, i;

unsigned char msg[1024] = "\xc2\x86\x69\x6d\x88\x7c\x9a\xa0\x61\x1b\xbb\x3e\x20\x25\xa4\x5a\xc2\x86\x69\x6d\x88\x7c\x9a\xa0\x61\x1b\xbb\x3e\x20\x25\xa4\x5a";



int rv;

OpenSSL_add_all_algorithms();

EVP_CIPHER_CTX_init(&ctx);



rv = EVP_DecryptInit_ex(&ctx, EVP_aes_128_cbc(),NULL, key, iv);

if(rv != 1)

{

printf("Error");

return -1;

}

outl = 0;

rv = EVP_DecryptUpdate(&ctx, out, &outl, msg, DATA_LEN);

if(rv != 1)

{

printf("Error");

return -1;

}

rv = EVP_DecryptFinal_ex(&ctx, out + outl, &tmp);

outl = outl + tmp;

printf("----cipher_algo is AES128 cipher_mode is CBC dec outdata is :-----------\n");

for(i = 0; i < DATA_LEN; i++)

printf("%02x ", out[i]);

printf("\r\n");

return 0;

}

编译:

[ufo@localhost fuck]$ gcc testdec_evp.c -Wall -g -lssl -lcrypto -o testdec

测试结果为:

[ufo@localhost fuck]$ ./testdec

----cipher_algo is AES128 cipher_mode is CBC dec outdata is :-----------

89 6b c4 4f 7d a4 3e de 21 a9 44 07 ff 44 95 88 89 6b c4 4f 7d a4 3e de 21 a9 44 07 ff 44 95 88
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: