今天书接上回,接着讨论本地pem格式存储密钥的问题。方世玉的干爹说过,功夫不用是会贬值的。今天我深刻的体会到了这一点,所以复习了好一会才恢复功力。
首先封装了ASN1
string对象的i2d和d2i函数
[code=c]
int i2d_string(void* a,unsigned char**
pp)
{
i2d_ASN1_bytes((ASN1_STRING*)a,pp,12,V_ASN1_UNIVERSAL);//((ASN1_STRING*)a)->type
}
ASN1_STRING
*d2i_string(ASN1_STRING **a, const unsigned char **in, long len)
{
return d2i_ASN1_bytes(a, in,
len, 12,
V_ASN1_UNIVERSAL);
}
[/code]
然后我再封装了串行化和反串行化函数
[code=c]
int
c2file(uint8_t *data,int len,const char* file,const char *name)
{
BIO
*bp;
int ret2;
bp=BIO_new_file(file,"w");
ASN1_STRING *str
= ASN1_STRING_type_new(V_ASN1_PRINTABLESTRING) ;
ASN1_STRING_set(str ,
data , len);
PEM_ASN1_write_bio(i2d_string,name,bp,str,EVP_des_ede3_cbc(),NULL,NULL,NULL,NULL);
/*ret2=PEM_write_bio(bp,name,"",data,len);
if(ret2 == 0)
{
cerr << "write data error" << endl;
return -1;
}*/
BIO_free(bp);
return 0;
}
int file2c(uint8_t
*cdata,int clen,const char* file,const char* cname)
{
BIO *bp;
char *name=NULL,*header=NULL;
unsigned char *data=NULL;
long len =
0;
int ret2;
BIO *bio_err=BIO_new_fp(stderr,BIO_NOCLOSE);
bp=BIO_new_file(file,"r");
/*
ret2=PEM_read_bio(bp,&name,&header,&data,&len);
if(ret2
== 0 )
{
cerr << "read data error " << len
<< endl;
return -1;
}
OPENSSL_free(name);
OPENSSL_free(header);
memcpy(cdata,data,min((int)len,clen));
OPENSSL_free(data);
*/
ASN1_STRING *str;
PEM_ASN1_read_bio((d2i_of_void*)d2i_string,cname,bp,(void**)&str,NULL,NULL);
if (!str)
{
BIO_printf(bio_err,"unable to load CRL\n");
ERR_print_errors(bio_err);
return -1;
}
memcpy(cdata,ASN1_STRING_data(str),min(ASN1_STRING_length(str),clen));
BIO_free(bp);
return
0;
}
[/code]
测试代码如下:
[code=c]
TEST(cip,cip)
{
cipher
cp;
cp.serial("kfile","ivfile");
}
TEST(cip1,cip1)
{
cipher cp;
cp.update("kfile","ivfile");
}
[/code]
测试结果:
[==========] Running 2
tests from 2 test cases.
[----------] Global test environment
set-up.
[----------] 1 test from cip
[ RUN ] cip.cip
Enter PEM
pass phrase:
Verifying - Enter PEM pass phrase:
Enter PEM pass
phrase:
Verifying - Enter PEM pass phrase:
[ OK ] cip.cip (4886
ms)
[----------] 1 test from cip (4886 ms total)
[----------] 1 test from
cip1
[ RUN ] cip1.cip1
Enter PEM pass phrase:
Enter PEM pass
phrase:
[ OK ] cip1.cip1 (2746 ms)
[----------] 1 test from cip1
(2746 ms total)
[----------] Global test environment
tear-down
[==========] 2 tests from 2 test cases ran. (7633 ms
total)
[ PASSED ] 2 tests.
阅读(4578) | 评论(0) | 转发(0) |