所有常见证书处理函数的实现



    // 转换私钥编码格式
    
    BOOL ConvertKeyFormat(char *oldKey,int oldKeyLen,int oldFormat,
     char *newKeyFile,int newFormat)
    {
     EVP_PKEY *key=NULL;
     BIO *biout=NULL;
     int ret;
    
     if ((biout=BIO_new_file(newKeyFile, "w")) == NULL)
     return false;
    
     key=LoadKey(oldKey,oldKeyLen,NULL,oldFormat);
     if(key)
     {
     if(newFormat==FORMAT_DER)
     ret=i2d_PrivateKey_bio(biout,key);
     if(newFormat==FORMAT_PEM)
     ret=PEM_write_bio_PrivateKey(biout, key, NULL, NULL, 0, 0, NULL);
     }
     else
     return false;
    
     BIO_free(biout);
     EVP_PKEY_free(key);
     return true;
    }
    
    /////////////////////////////////////////////////////////////////////////////
    // 根据公私钥生成P12格式证书
    
    BOOL CreateP12Cert(char *pubCertFile,char *priCertFile,int oldFormat,
     char *p12CertFile,char *p12pass)
    {
     EVP_PKEY *key=NULL;
     X509 *cert=NULL;
     PKCS12 *p12;
    
     cert=LoadCert(pubCertFile,0,NULL,oldFormat);
     key=LoadKey(priCertFile,0,NULL,oldFormat);
    
     SSLeay_add_all_algorithms();
     p12=PKCS12_create(p12pass,"(SecPass)", key, cert, NULL, 0,0,0,0,0);
     if(!p12)
     {
     X509_free(cert);
     EVP_PKEY_free(key);
     return false;
     }
    
     FILE * fp=fopen(p12CertFile, "wb");
     i2d_PKCS12_fp(fp, p12);
     PKCS12_free(p12);
     fclose(fp);
    
     X509_free(cert);
     EVP_PKEY_free(key);
     EVP_cleanup();
     return true;
    }
    
    /////////////////////////////////////////////////////////////////////////////
    // 解析P12格式证书为公钥和私钥
  

你可能感兴趣的:(编程技术)