我用signtool给我的应用程序签名了,怎么样使用Crypto API来安装证书呢?

解决方案 »

  1.   

    直接使用OPENSSL进行签名、验证更方便
    证书无需安装,P12、PEM都可以直接用OPENSSL打开提供个个人写的签名的方法
    bool COpenSSL_ce::SignMessage(const char *sP12file, const char *sPsw, const unsigned char *sMsg, int cbMsg, unsigned char *sSignMsg, int &cbSignMsg)
    {
    bool bret=false;
    BIO * bio=NULL;
    BIO *out=NULL;
    PKCS12 *p12 = NULL;
    unsigned char p12Buff[MAX_P12BUFF]={0};
    unsigned int  p12BuffLen=0;
    unsigned char pSignBuff[MAX_SIGN_MSG]={0};
    unsigned int  iSignLen=-1;
    EVP_PKEY *pkey = NULL;
    X509 *SignCert = NULL;
    EVP_MD_CTX *mdctx=NULL; //从文件读P12数据
    FILE *fp = fopen(sP12file, "rb");
    if(fp==NULL) goto OL_FINNALY;
    p12BuffLen = fread(p12Buff, 1, MAX_P12BUFF, fp);
    fclose(fp);
    if(p12BuffLen<=0) goto OL_FINNALY; OpenSSL_add_all_algorithms();
    //把P12文件转化为PKCS12
    bio = BIO_new(BIO_s_mem());
    BIO_write(bio, p12Buff, p12BuffLen);
    p12 = d2i_PKCS12_bio(bio, NULL);
    if(p12==NULL)
    {
    goto OL_FINNALY;
    } //获得私钥
    int rv = PKCS12_parse(p12, sPsw, &pkey, &SignCert,NULL);
    if(rv != 1)
    {
    goto OL_FINNALY;
    } //进行签名  --  摘要算法为MD5
    mdctx=new EVP_MD_CTX;
    EVP_MD_CTX_init(mdctx);
    if(!EVP_SignInit_ex(mdctx, EVP_md5(), NULL))
    {
    goto OL_FINNALY;
    } int offset=0;
    for(;;)
    {
    if(cbMsg-offset<=MAX_SIGN_MSG)
    {
    if(!EVP_SignUpdate(mdctx, sMsg+offset, cbMsg-offset))
    goto OL_FINNALY;
    break;
    }
    else
    {
    if(!EVP_SignUpdate(mdctx, sMsg+offset, MAX_SIGN_MSG))
    goto OL_FINNALY;
    offset+=MAX_SIGN_MSG;
    }
    }
    if(!EVP_SignFinal(mdctx, pSignBuff, &iSignLen, pkey))
    {
    goto OL_FINNALY;
    }
    //对签名进行64位编码
    EVP_ENCODE_CTX ctxEn;
    EVP_EncodeInit(&ctxEn);
    if(!(cbSignMsg=EVP_EncodeBlock(sSignMsg, pSignBuff, iSignLen)) || iSignLen==-1)
    {
    goto OL_FINNALY;
    }
    bret=true;OL_FINNALY:
    if(bio)
    BIO_free(bio);
    if(p12)
    PKCS12_free(p12);
    if(pkey)
    EVP_PKEY_free(pkey);
    if(SignCert)
    X509_free(SignCert);
    if(mdctx)
    {
    EVP_MD_CTX_cleanup(mdctx);
    delete mdctx;
    mdctx=NULL;
    }
    return bret;
    }