标签:
1 // TestOpensslP7Envelope.cpp : 定义控制台应用程序的入口点。 2 // 3 4 #include "stdio.h" 5 #include "string.h" 6 #include "stdlib.h" 7 8 #include <openssl/pem.h> 9 #include <openssl/pkcs7.h> 10 #include <openssl/objects.h> 11 #include <openssl/x509.h> 12 13 14 15 int main() 16 { 17 18 19 EVP_PKEY *priKey; 20 21 //读取公钥证书 22 23 char buf[4096]; 24 unsigned char *p; 25 char *DerPathCharp = "/Users/ipc/Desktop/openssl/rsa_encode_decode/CryptoDemo/yaclifecert.der"; 26 27 FILE* fp=fopen(DerPathCharp,"rb"); 28 29 if(!fp) 30 return NULL; 31 32 int len=fread(buf,1,4096,fp); 33 34 fclose(fp); 35 36 37 p=(unsigned char *)buf; 38 39 X509 *x509_Cert=X509_new(); 40 41 d2i_X509(&x509_Cert,(const unsigned char **)&p,len); 42 43 44 //调用openssl的代码如下: 45 46 PKCS7* p7 = PKCS7_new(); 47 48 49 //设置类型为NID_pkcs7_enveloped 50 51 PKCS7_set_type(p7, NID_pkcs7_enveloped); 52 53 //DES算法,用于加密内容“How are you!” 54 55 const EVP_CIPHER *evp_cipher = EVP_des_cbc(); 56 57 PKCS7_set_cipher(p7,evp_cipher); 58 59 60 61 //设置接收者证书,获取公钥用于加密对称密钥 62 63 PKCS7_RECIP_INFO *p7recipinfo = PKCS7_add_recipient(p7,x509_Cert); 64 65 BIO *p7bio = PKCS7_dataInit(p7, NULL); 66 char *instr = "How Are You!"; 67 BIO_write(p7bio,instr,strlen(instr)); 68 69 70 printf("instr = %s",instr); 71 //完成数字信封的运算 72 BIO_flush(p7bio); 73 74 PKCS7_dataFinal(p7, p7bio); 75 76 //转换PKCS7结构体为DER编码 77 //X509* derTmp,*der; 78 int derLen = i2d_PKCS7(p7,NULL); 79 const unsigned char * der = (unsigned char*)malloc(derLen); 80 81 unsigned char * derTmp =(unsigned char*)der; 82 //转换为der编码输出 83 derLen = i2d_PKCS7(p7,&derTmp); 84 85 86 BIO_free(p7bio); 87 88 PKCS7_free(p7); 89 90 91 92 93 94 95 96 97 //解P7数字信封的代码: 98 99 //der编码转换为PKCS7结构体 100 int derP7EnvelopedDataLen = derLen; 101 PKCS7* v_p7 = NULL; 102 103 PKCS7* v_p7_tmp = d2i_PKCS7(&v_p7,&der,derP7EnvelopedDataLen); 104 105 106 107 //解析出原始数据, evp_key:接收者私钥,x509_cert:接收者证书 108 BIO * v_p7bio_tmp = BIO_new(BIO_s_file()); 109 BIO * v_p7bio = PKCS7_dataDecode(v_p7,priKey,NULL,x509_Cert); 110 111 //从BIO中读取原始数据,将得到"How are you!" 112 char src[4096]; 113 int srcLen = BIO_read(v_p7bio,src,4096); 114 115 printf("\nsrc = %s",src); 116 if (!strcmp(instr,src)) 117 { 118 printf(" \n ssl_PKCS7_get_Enveloped_data ok !!\n"); 119 } 120 121 BIO_free(v_p7bio); 122 123 PKCS7_free(v_p7); 124 return NULL; 125 }
标签:
原文地址:http://www.cnblogs.com/ggxxjj123/p/4515715.html