Skip to main content

RSA encryption and decryption

The Crypto Interface supports padding modes PKCS #1 v1.5 and PKCS-OAEP.

PKCS #1 v1.5 padding mode

The PKCS #1 v1.5 padding mode may be used to encrypt data by calling:

CRYPTO_INTERFACE_RSA_encryptAux(pPubKey, pMessage, messageLen, pCipher, RANDOM_rngFun, g_pRandomContext, NULL);

where pPubKey is an instance of an RSAKey containing a public key. Because PKCS #1 v1.5 requires at least 11 padding bytes, messageLen must not exceed the key size (i.e., the RSA-modulus size) in bytes minus 11. For example, if the key size is 2048 bits, then messageLen can be no bigger than 245 bytes. The buffer pCipher holds the resulting cipher text and must have a length of (at least) the key size in bytes.

In this example, the callback method RANDOM_rngFun is used, the global random context g_pRandomContext is defined in ${MSS_SRC_PKG}/src/common/random.h, and the vlong queue is NULL.

To decrypt the key, call:

CRYPTO_INTERFACE_RSA_decryptAux(pPrivKey, pCipher, pPlain, &plainLen, NULL, NULL, NULL);

where pPrivKey is an instance of an RSAKey containing either a private key or the private/public keypair. The buffer pPlain must have enough space for the recovered plaintext, and plainLen is set to the length of the recovered plaintext in bytes. For implementations with exponent blinding as a security feature, an RNG callback and context may be passed in the third- and second-to-last parameters. The final parameter is for the vlong queue.

PKCS-OAEP padding mode

For PKCS-OAEP, use the following APIs:

  • CRYPTO_INTERFACE_PKCS1_rsaOaepEncrypt(g_pRandomContext, pPubKey, hashAlgo, MOC_PKCS1_ALG_MGF1, hashAlgo, pMessage, messageLen, pLabel, labelLen, &pCipherText, &cipherTextLen);
  • CRYPTO_INTERFACE_PKCS1_rsaOaepDecrypt(pPrivKey, hashAlgo, MOC_PKCS1_ALG_MGF1, hashAlgo, pCipherText, cipherTextLen, pLabel, labelLen, &pPlainText, &plainTextLen);

As already mentioned, OAEP padding uses a mask generation function (MGF) based on a digest algorithm. The NanoCrypto implementation supports only the standard MGF1 identified by MOC_PKCS1_ALG_MGF1. Moreover, hashAlgo, one of the digest algorithm identifiers found in ${MSS_SRC_PKG}/src/crypto.h, such as ht_sha256, must be the same for the padding and MGF; hence, it is used in both the second and fourth parameters. Recall that OAEP allows for an optional buffer of bytes called pLabel. Also note that these APIs, unlike those for PKCS #1 v1.5, allocate a buffer for the result and set the output params pCipherText or pPlainText, respectively, to the location of that buffer. The cipherTextLen or plainTextLen variables are set to the length of those buffers, respectively.

Complete example

A complete example of RSA encryption and decryption may be found at:

${MSS_SRC_PKG}/src/crypto_interface/example/crypto_interface_rsa_example.c