3

I have a DER certificate from which I am retrieving the Public key in unsigned char buffer as following, is it the right way of getting?

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);

And, With this unsigned char buffer, How do I get back the EVP_PKEY for RSA? OR Can I use following ???,

EVP_PKEY *d2i_PublicKey(int type, EVP_PKEY **a, unsigned char **pp, long length);
int i2d_PublicKey(EVP_PKEY *a, unsigned char **pp);
openssid
  • 711
  • 3
  • 8
  • 18

2 Answers2

9

The following openssl API works for unsigned char buffer to 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);

And, the following works for Convert EVP_PKEY to unsigned char buffer.

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]);
}

Thanks-opensid

openssid
  • 711
  • 3
  • 8
  • 18
3

Convert EVP_PKEY to character buffer.

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;
}
  • This creates an output `-----BEGIN PRIVATE KEY-----` if anyone like me looking for `-----BEGIN PUBLIC KEY-----` replace with below like in above function ```if (0 == PEM_write_bio_PUBKEY(bio, pkey)){``` – PravyNandas Feb 03 '23 at 15:28