利用openssl库实现BIO加密

来源:互联网 发布:天猫是淘宝旗下的吗 编辑:程序博客网 时间:2024/05/20 18:44

最近在工作之余,研究了下openssl的代码,想尝试着写一篇如何利用openssl中的crypto实现数据的加密;后期再更新通过加密算法加密TCP数据,也是希望可以在工作可以用到;
以下就是源代码,其实在编写这个代码的时候也发现了 一个openssl库中的一个接口的问题,但是已经被修复了。
在openssl-1.0.2l中的static long enc_ctrl(BIO *b, int cmd, long num, void *ptr)接口中没有对ptr这个指针做NULL检查,在master版已经被修复了。
总结:要参与到开源项目中就要多用它的代码,多搭环境测试。
唉,上班就休息一天,还是看代码,对自己也是无语了,匿了;

/* main */#include <stdlib.h>#include <openssl/rsa.h>       /* SSLeay stuff */#include <openssl/crypto.h>#include <openssl/x509.h>#include <openssl/pem.h>#include <openssl/ssl.h>#include <openssl/err.h>#include <openssl/bio.h>#include <openssl/evp.h>#define SIZE    (512)#define BSIZE   (8*1024)void initssl(){    CRYPTO_malloc_init();    ERR_load_crypto_strings();     OpenSSL_add_all_algorithms();}int main(){    int ret = -1;    BIO *enc = NULL,*in,*out=NULL;    EVP_CIPHER  *cipher = NULL,*c;    EVP_CIPHER_CTX *ctx = NULL;    int benc = 1;    unsigned char *buff = NULL;    int bsize = BSIZE;    initssl();    printf("come here ----- \n");    out = BIO_new_fp(stderr,BIO_NOCLOSE);    if(out == NULL)    {        printf("out null\n");        exit(1);    }    printf("out OK\n");    in = BIO_new_file("a.txt","r");    if( (enc = BIO_new(BIO_f_cipher())) == NULL)    {        BIO_printf(out,"Cipher New BIO Error\n");        exit(1);    }    if( (c = EVP_get_cipherbyname("des")) == NULL)    {        BIO_printf(out,"EVP_get_cipherbyname Error\n");        exit(2);    }    cipher = c;    BIO_get_cipher_ctx(enc, &ctx);    if(ctx == NULL)    {        BIO_printf(out,"ctx null\n");        exit(3);    }    if (!EVP_CipherInit_ex(ctx, cipher, NULL, NULL, NULL, benc)) {        BIO_printf(out,"EVP_CipherInit_ex Error\n");        exit(3);    }    enc = BIO_push(enc,out);    buff = (unsigned char *)OPENSSL_malloc(EVP_ENCODE_LENGTH(bsize));    if(buff == NULL)    {        BIO_printf(out,"buff malloc error\n");        exit(1);    }    ret = BIO_read(in,(char *)buff,bsize);    if(ret < 0)    {        BIO_printf(out,"BIO_read Error\n");        exit(11);    }    BIO_printf(out,"buff = %s\n",buff);    BIO_write(enc,(char *)buff,bsize);      return 0;}