Path: blob/master/libs/tomcrypt/src/pk/rsa/rsa_encrypt_key.c
4396 views
/* LibTomCrypt, modular cryptographic library -- Tom St Denis1*2* LibTomCrypt is a library that provides various cryptographic3* algorithms in a highly modular and flexible manner.4*5* The library is free for all purposes without any express6* guarantee it works.7*/8#include "tomcrypt.h"910/**11@file rsa_encrypt_key.c12RSA PKCS #1 encryption, Tom St Denis and Andreas Lange13*/1415#ifdef LTC_MRSA1617/**18(PKCS #1 v2.0) OAEP pad then encrypt19@param in The plaintext20@param inlen The length of the plaintext (octets)21@param out [out] The ciphertext22@param outlen [in/out] The max size and resulting size of the ciphertext23@param lparam The system "lparam" for the encryption24@param lparamlen The length of lparam (octets)25@param prng An active PRNG26@param prng_idx The index of the desired prng27@param hash_idx The index of the desired hash28@param padding Type of padding (LTC_PKCS_1_OAEP or LTC_PKCS_1_V1_5)29@param key The RSA key to encrypt to30@return CRYPT_OK if successful31*/32int rsa_encrypt_key_ex(const unsigned char *in, unsigned long inlen,33unsigned char *out, unsigned long *outlen,34const unsigned char *lparam, unsigned long lparamlen,35prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key)36{37unsigned long modulus_bitlen, modulus_bytelen, x;38int err;3940LTC_ARGCHK(in != NULL);41LTC_ARGCHK(out != NULL);42LTC_ARGCHK(outlen != NULL);43LTC_ARGCHK(key != NULL);4445/* valid padding? */46if ((padding != LTC_PKCS_1_V1_5) &&47(padding != LTC_PKCS_1_OAEP)) {48return CRYPT_PK_INVALID_PADDING;49}5051/* valid prng? */52if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {53return err;54}5556if (padding == LTC_PKCS_1_OAEP) {57/* valid hash? */58if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {59return err;60}61}6263/* get modulus len in bits */64modulus_bitlen = mp_count_bits( (key->N));6566/* outlen must be at least the size of the modulus */67modulus_bytelen = mp_unsigned_bin_size( (key->N));68if (modulus_bytelen > *outlen) {69*outlen = modulus_bytelen;70return CRYPT_BUFFER_OVERFLOW;71}7273if (padding == LTC_PKCS_1_OAEP) {74/* OAEP pad the key */75x = *outlen;76if ((err = pkcs_1_oaep_encode(in, inlen, lparam,77lparamlen, modulus_bitlen, prng, prng_idx, hash_idx,78out, &x)) != CRYPT_OK) {79return err;80}81} else {82/* PKCS #1 v1.5 pad the key */83x = *outlen;84if ((err = pkcs_1_v1_5_encode(in, inlen, LTC_PKCS_1_EME,85modulus_bitlen, prng, prng_idx,86out, &x)) != CRYPT_OK) {87return err;88}89}9091/* rsa exptmod the OAEP or PKCS #1 v1.5 pad */92return ltc_mp.rsa_me(out, x, out, outlen, PK_PUBLIC, key);93}9495#endif /* LTC_MRSA */969798