来自x509中的char缓冲区的EVP_PKEY(PKCS7)

时间:2010-05-27 06:22:01

标签: openssl

我有一个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);

并且,使用此unsigned char缓冲区,如何获取RSA的EVP_PKEY? OR 我可以使用以下???,

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

2 个答案:

答案 0 :(得分:8)

以下openssl API适用于无符号字符缓冲区到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);

并且,以下适用于将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

答案 1 :(得分:0)

将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;
}