Topic: Rsa encryption using x509 certificate.

I'm trying to do an rsa 4096 encryption and decryption using a certificate.
This is the encryption code I have so far:

byte *EncryptRSAStringKey(const byte* cert, const char* message, word32 messageSize)
{
    RsaKey key;
    WC_RNG rng;
    byte* der;
    byte* encryptedData;
    word32 encryptedDataSize;
    int ret;

    ret = wc_InitRsaKey(&key, NULL);

    if (ret != 0)
        return NULL;

    ret = wc_InitRng(&rng);

    if (ret != 0)
    {
        wc_FreeRsaKey(&key);
        return NULL;
    }

    key.rng = &rng;

    der = (byte*)calloc(1, 4096);

    if (der == NULL)
    {
        wc_FreeRsaKey(&key);
        wc_FreeRng(&rng);
        return NULL;
    }

    ret = wc_CertPemToDer(cert, 4096, der, 4096, CERT_TYPE);
    if (ret < 0)
    {
        wc_FreeRsaKey(&key);
        wc_FreeRng(&rng);
        free(der);
        return NULL;
    }

    word32 idx = 0;
    ret = wc_RsaPublicKeyDecode(der, &idx, &key, 4096);
    if (ret < 0)
    {
        wc_FreeRsaKey(&key);
        wc_FreeRng(&rng);
        free(der);
        return NULL;
    }

    encryptedDataSize = wc_RsaEncryptSize(&key);
    encryptedData = (byte*)calloc(encryptedDataSize, sizeof(byte));

    if (encryptedData == NULL)
    {
        wc_FreeRsaKey(&key);
        wc_FreeRng(&rng);
        free(der);
        return NULL;
    }

    ret = wc_RsaPublicEncrypt((const byte*)message, messageSize, encryptedData, encryptedDataSize, &key, key.rng);

    if (ret < 0)
    {
        wc_FreeRsaKey(&key);
        wc_FreeRng(&rng);
        free(der);
        free(encryptedData);
        return NULL;
    }

    wc_FreeRsaKey(&key);
    wc_FreeRng(&rng);

    return encryptedData;
}

I get error code -140 from the wc_RsaPublicKeyDecode function. Which steps am I missing here?

Share

Re: Rsa encryption using x509 certificate.

Hi lazH,

Your code is currently passing in the entire certificate DER to wc_RsaPublicKeyDecode, this won't work as wc_RsaPublicKeyDecode expects just the key.
You will need to call wolfSSL_X509_load_certificate_file followed by wolfSSL_X509_get_pubkey on your certificate to extract the public key.  You can then call wc_RsaPublicKeyDecode on this extracted public key and use it as desired for encryption/decryption.
Check out our full example of this here: https://github.com/wolfSSL/wolfssl-exam … m-certfile

Thanks,
Kareem

Share

Re: Rsa encryption using x509 certificate.

Thank you, that's what I was missing.

Share