openssl blowfish 加密解密


前面对AES的使用进行了研究,这一节,介绍Blowfish,Blowfish也是一种对称加密算法,采用分组加密的模式。


C/C++采用openssl/crypt库调用,过程比较简单,直接看下面代码:

#include 

#include "evp.h" 

#define BREAK_ERROR(msg){\
    fprintf(stderr,"error break [%s]\n",msg);\
    break;\
}

#define CIPHER_INFO(e){\
    fprintf(stderr,"key_len:[%d]",EVP_CIPHER_CTX_key_length(e));\
    fprintf(stderr,"iv_len :[%d]",EVP_CIPHER_CTX_iv_length(e));\
    fprintf(stderr,"mode:[%d]",EVP_CIPHER_CTX_mode(e));\
    fprintf(stderr,"flag:[%d]\n",EVP_CIPHER_CTX_flags(e));\
}

int test_ecb_blowfish(char *buf1,char *buf2,char *buf3,int *len1,int *len2,int *len3,unsigned char *key){
    int ret = 0,tmplen;
    *len2 = *len3 = tmplen = 0; 

    /* encrypt */
    EVP_CIPHER_CTX ctx;
    EVP_CIPHER_CTX_init(&ctx);
    EVP_EncryptInit_ex(&ctx,EVP_bf_ecb(),NULL,key,NULL);
    CIPHER_INFO(&ctx);
    do{
    	if(!EVP_EncryptUpdate(&ctx,buf2,len2,buf1,*len1)){
	    BREAK_ERROR("encryptupdate");
    	}
    	if(!EVP_EncryptFinal_ex(&ctx,buf2+(*len2),&tmplen)){
	    BREAK_ERROR("encryptfinal");
    	}
    }while(0);
    *len2 = *len2 + tmplen;
    EVP_CIPHER_CTX_cleanup(&ctx);
    fprintf(stderr,"encrypt:len1:[%d] len2:[%d]\n",*len1,*len2);

    /* decrypt */
    EVP_CIPHER_CTX ctx_d;
    EVP_CIPHER_CTX_init(&ctx_d);
    EVP_DecryptInit_ex(&ctx_d,EVP_bf_ecb(),NULL,key,NULL);
    CIPHER_INFO(&ctx_d);
    do{
	if(!EVP_DecryptUpdate(&ctx_d,buf3,len3,buf2,*len2)){
	    BREAK_ERROR("decryptupdate");
    	}
	if(!EVP_DecryptFinal(&ctx_d,buf3+(*len3),&tmplen)){
	    BREAK_ERROR("decryptfinal");
	}
    }while(0);
    *len3 = *len3 + tmplen;
    EVP_CIPHER_CTX_cleanup(&ctx_d);
    fprintf(stderr,"encrypt:len2:[%d] len3:[%d]\n",*len2,*len3);
    /* compare the data */
    if(memcmp(buf1,buf3,*len1) == 0){
	fprintf(stderr,"%s success\n",__func__);
    }else{
	fprintf(stderr,"%s failed\n",__func__);
    }
    return 0;	
}

#define BUF_SIZE 102402
int main(int argc,char ** argv){
    int i,len1,len2,len3;
    unsigned char key_8[] = {0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15};
    char * buf1 = (char *)malloc(BUF_SIZE + 1);
    char * buf2 = (char *)malloc(BUF_SIZE + 128);
    char * buf3 = (char *)malloc(BUF_SIZE + 128);
    len1 = len2 = len3 = BUF_SIZE;
    for(i = 0;i< BUF_SIZE;i++){
	buf1[i] = i%256;
    }
    test_ecb_blowfish(buf1,buf2,buf3,&len1,&len2,&len3,key_8);

    return 0;
}
//
// 标准ECB模式进行加密解密处理。
//

以上代码是运行在 openssl-0.9.8zd 版本下通过测试的。不确定是否在openssl所有版本上面都可以运行。在使用是请亲测。


你可能感兴趣的:(系统综合,C,数据安全)