[转载]借助openssl解析ECC公钥

void GetPubKey(const char* FilePath, char* PubKey)
{
    unsigned char Cert[4099];
    unsigned char *pTmp = NULL;
    FILE *fp = NULL;
    fp=fopen(FilePath,“rb”);
    if( NULL != fp)
    {
        X509 *usrCert = NULL; //X509证书结构体,保存用户证书
        unsigned long Certlen = 0;
        Certlen=fread(Cert,1,4096,fp);
        fclose(fp);
//判断是否为DER编码的用户证书,并转化为X509结构体
        pTmp = Cert;
//usrCert = d2i_X509(NULL,(const unsigned char ** )&pTmp,Certlen);

//if( NULL == usrCert)
        {
            BIO b;
            / 判断是否为PEM格式的数字证书 */
            b=BIO_new_file(FilePath,“r”);
            PEM_read_bio_X509(b, &usrCert, NULL, NULL);
            BIO_free(b);
            if(usrCert==NULL)
            {
                return;
            }
        }
//保存证书公钥
        int derpubkeyLen = 0;
        EVP_PKEY pubKeytemp = NULL;
        pTmp = NULL;
        char HexKey = NULL;
//获取证书公钥
        pubKeytemp = X509_get_pubkey(usrCert);
        if (!pubKeytemp)
            return;

        X509_PUBKEY * pubKeytempss;
        pubKeytempss = X509_get_X509_PUBKEY(usrCert);
        derpubkeyLen = i2d_PublicKey(pubKeytemp, NULL);
        if(derpubkeyLen < 1)
            return;

        unsigned char* buf = NULL;
        buf = (unsigned char*)malloc(derpubkeyLen);
        i2d_PublicKey(pubKeytemp,&buf);

        EC_KEY ec_key = EVP_PKEY_get0_EC_KEY(pubKeytemp);
        if (!ec_key)
            return;
        int buflen = EC_KEY_key2buf(ec_key, EC_KEY_get_conv_form(ec_key),(unsigned char)&pTmp, NULL);
        *

        BIGNUM *pub_key_BIGNUM;
        pub_key_BIGNUM = BN_new();
        BN_bin2bn(pTmp, buflen, pub_key_BIGNUM);
        HexKey = BN_bn2hex(pub_key_BIGNUM);
        strcpy(PubKey,HexKey);

        EVP_PKEY_free(pubKeytemp);
        X509_free(usrCert);

    }

}

其中斜体部分也可以利用如下代码替换
EC_POINT pub_key;
unsigned char pubbuf[1024] = { 0 };//公钥数据
pub_key = (EC_POINT)EC_KEY_get0_public_key(ec_key);
EC_GROUP* group = (EC_GROUP*)EC_KEY_get0_group(ec_key);
int buflen = EC_POINT_point2oct(group, pub_key, EC_KEY_get_conv_form(ec_key), pubbuf, sizeof(pubbuf), NULL);

还有另外一种如下:
ASN1_BIT_STRING * pubkey;
pubkey = X509_get0_pubkey_bitstr(usrCert);
int nlen = pubkey->length;
pubkey->data

 

即为其公钥数据。

原文链接:https://blog.csdn.net/Elsa_Zhang/article/details/88190769

 

上一篇:AWS EC 主机无法通过 PHP 连接 RDS MySQL


下一篇:c++17 optional 简介