【问题标题】:EVP_PKEY from char buffer in x509 (PKCS7)来自 x509 (PKCS7) 中字符缓冲区的 EVP_PKEY
【发布时间】:2010-05-27 06:22:01
【问题描述】:

我有一个 DER 证书,我正在从中检索 unsigned char 缓冲区中的公钥,如下所示,这是正确的获取方式吗?

pStoredPublicKey = X509_get_pubkey(x509);
if(pStoredPublicKey == NULL)
{
        printf(": publicKey is NULL\n");
}
if(pStoredPublicKey->type == EVP_PKEY_RSA) {
        RSA *x = pStoredPublicKey->pkey.rsa;
        bn = x->n;
}
else if(pStoredPublicKey->type == EVP_PKEY_DSA) {

}
else if(pStoredPublicKey->type == EVP_PKEY_EC) {
}
else {
        printf(" : Unkown publicKey\n");
}
//extracts the bytes from public key & convert into unsigned char buffer
buf_len = (size_t) BN_num_bytes (bn);
key = (unsigned char *)malloc (buf_len);
n = BN_bn2bin (bn, (unsigned char *) key);
for (i = 0; i < n; i++)
{
        printf("%02x\n", (unsigned char) key[i]);
}
keyLen = EVP_PKEY_size(pStoredPublicKey);
EVP_PKEY_free(pStoredPublicKey);

而且,使用这个无符号字符缓冲区,我如何取回 RSA 的 EVP_PKEY? 我可以使用以下???,

EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, unsigned char **pp, long length);
int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp);

【问题讨论】:

    标签: openssl


    【解决方案1】:

    以下 openssl API 适用于 EVP_PKEY 的 unsigned char 缓冲区,

    EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, unsigned char **pp, long length);
    int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp);
    

    并且,以下适用于将 EVP_PKEY 转换为无符号字符缓冲区。

    int pkeyLen;
    unsigned char *ucBuf, *uctempBuf;
    pkeyLen = i2d_PublicKey(pkey, NULL);
    ucBuf = (unsigned char *)malloc(pkeyLen+1);
    uctempBuf = ucBuf;
    i2d_PublicKey(pkey, &uctempBuf);
    int ii;
    for (ii = 0; ii < pkeyLen; ii++)
    {
            printf("%02x\n", (unsigned char) ucBuf[ii]);
    }
    

    谢谢-opensid

    【讨论】:

      【解决方案2】:

      将 EVP_PKEY 转换为字符缓冲区。

      char *EVP_PKEY_to_PEM (EVP_PKEY *pkey)
      {
          BIO *bio = NULL;
          char *pem = NULL;
      
          if (NULL == pkey)
            return NULL;
      
          if ((bio = BIO_new(BIO_s_mem())) == NULL)
            return NULL;
      
          if (0 == PEM_write_bio_PrivateKey(bio, pkey, NULL, NULL, 0, NULL, NULL)){
            BIO_free(bio);
            return NULL;
          }
      
          pem = (char *) calloc(1, bio->num_write + 1);
          BIO_read(bio, pem, bio->num_write);
          BIO_free(bio);
      
          return pem;
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-01-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-10-13
        • 2016-04-06
        • 1970-01-01
        相关资源
        最近更新 更多