日期:2014-05-16  浏览次数:20832 次

linux下安装openssl和调用openssl接口(经过本人测试)

linux下安装openssl和调用openssl接口

下面以ubuntu为例:

第一步:安装openssl软件,sudo apt-get install openssl(其他linux操作系统,有相应的软件安装命令)

第二步:安装openssl库,sudo apt-get install libssl-dev 

完成这两步就可以在控制台使用openssl命令和在程序里调用openssl提供的接口了

如:openssl aes-128-cbc -in hello.txt -out hello.out -e -K 26896cd652fef3f547b46f6664e4cc29 -iv 00000000000000000000000000000000

调用openssl接口的例子为:




#include <openssl/evp.h>
#include<stdio.h>
#include<string.h>

int do_encrypt(unsigned char *iv, unsigned char *key, unsigned char*inBuffer, int inLen, unsigned char *outBuffer, int* pOutLen)
{
int tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_EncryptInit_ex(&ctx,EVP_aes_128_cbc(), NULL, key, iv);
if(!EVP_EncryptUpdate(&ctx, outBuffer, pOutLen, inBuffer, inLen))
{
return 0;
}
if(!EVP_EncryptFinal_ex(&ctx, outBuffer + *pOutLen, &tmplen))
{
return 0;
}
*pOutLen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
return 1;
}


int do_decrypt(unsigned char *iv, unsigned char *key, unsigned char*inBuffer, int inLen, unsigned char *outBuffer, int* pOutLen)
{
int tmplen;
EVP_CIPHER_CTX ctx;
EVP_CIPHER_CTX_init(&ctx);
EVP_DecryptInit_ex(&ctx,EVP_aes_128_cbc(), NULL, key, iv);
if(!EVP_DecryptUpdate(&ctx, outBuffer, pOutLen, inBuffer, inLen))
{
return 0;
}
if(!EVP_DecryptFinal_ex(&ctx, outBuffer + *pOutLen, &tmplen))
{
return 0;
}
*pOutLen += tmplen;
EVP_CIPHER_CTX_cleanup(&ctx);
return 1;
}


int main()
{
char *iv=(char *)malloc(35*sizeof(char));
char *key=(char *)malloc(35*sizeof(char));
unsigned char *inBuffer="hello,world";
unsigned char *outBuffer=(char *)malloc(35*sizeof(char));
int outlen=0;
int ret=0;
int i=0;
unsigned char *inBuffer_new=(char *)malloc(35*sizeof(char));
int inlen_new=0;


printf("input the key:\n");
gets(key);