1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis 2 * 3 * LibTomCrypt is a library that provides various cryptographic 4 * algorithms in a highly modular and flexible manner. 5 * 6 * The library is free for all purposes without any express 7 * guarantee it works. 8 * 9 * Tom St Denis, tomstdenis (at) gmail.com, http://libtomcrypt.com 10 */ 11 #include "tomcrypt.h" 12 13 /** 14 @file rsa_encrypt_key.c 15 RSA PKCS #1 encryption, Tom St Denis and Andreas Lange 16 */ 17 18 #ifdef MRSA 19 20 /** 21 (PKCS #1 v2.0) OAEP pad then encrypt 22 @param in The plaintext 23 @param inlen The length of the plaintext (octets) 24 @param out [out] The ciphertext 25 @param outlen [in/out] The max size and resulting size of the ciphertext 26 @param lparam The system "lparam" for the encryption 27 @param lparamlen The length of lparam (octets) 28 @param prng An active PRNG 29 @param prng_idx The index of the desired prng 30 @param hash_idx The index of the desired hash 31 @param padding Type of padding (LTC_PKCS_1_OAEP or LTC_PKCS_1_V1_5) 32 @param key The RSA key to encrypt to 33 @return CRYPT_OK if successful 34 */ 35 int rsa_encrypt_key_ex(const unsigned char *in, unsigned long inlen, 36 unsigned char *out, unsigned long *outlen, 37 const unsigned char *lparam, unsigned long lparamlen, 38 prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key) 39 { 40 unsigned long modulus_bitlen, modulus_bytelen, x; 41 int err; 42 43 LTC_ARGCHK(in != NULL); 44 LTC_ARGCHK(out != NULL); 45 LTC_ARGCHK(outlen != NULL); 46 LTC_ARGCHK(key != NULL); 47 48 /* valid padding? */ 49 if ((padding != LTC_PKCS_1_V1_5) && 50 (padding != LTC_PKCS_1_OAEP)) { 51 return CRYPT_PK_INVALID_PADDING; 52 } 53 54 /* valid prng? */ 55 if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) { 56 return err; 57 } 58 59 if (padding == LTC_PKCS_1_OAEP) { 60 /* valid hash? */ 61 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) { 62 return err; 63 } 64 } 65 66 /* get modulus len in bits */ 67 modulus_bitlen = mp_count_bits( (key->N)); 68 69 /* outlen must be at least the size of the modulus */ 70 modulus_bytelen = mp_unsigned_bin_size( (key->N)); 71 if (modulus_bytelen > *outlen) { 72 *outlen = modulus_bytelen; 73 return CRYPT_BUFFER_OVERFLOW; 74 } 75 76 if (padding == LTC_PKCS_1_OAEP) { 77 /* OAEP pad the key */ 78 x = *outlen; 79 if ((err = pkcs_1_oaep_encode(in, inlen, lparam, 80 lparamlen, modulus_bitlen, prng, prng_idx, hash_idx, 81 out, &x)) != CRYPT_OK) { 82 return err; 83 } 84 } else { 85 /* PKCS #1 v1.5 pad the key */ 86 x = *outlen; 87 if ((err = pkcs_1_v1_5_encode(in, inlen, LTC_PKCS_1_EME, 88 modulus_bitlen, prng, prng_idx, 89 out, &x)) != CRYPT_OK) { 90 return err; 91 } 92 } 93 94 /* rsa exptmod the OAEP or PKCS #1 v1.5 pad */ 95 return ltc_mp.rsa_me(out, x, out, outlen, PK_PUBLIC, key); 96 } 97 98 #endif /* MRSA */ 99 100 /* $Source: /cvs/libtom/libtomcrypt/src/pk/rsa/rsa_encrypt_key.c,v $ */ 101 /* $Revision: 1.8 $ */ 102 /* $Date: 2006/11/01 09:18:22 $ */ 103