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

/*********************************************************************
 * 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


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值