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?