1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis
3 * LibTomCrypt is a library that provides various cryptographic
4 * algorithms in a highly modular and flexible manner.
6 * The library is free for all purposes without any express
9 * Tom St Denis, tomstdenis@gmail.com, http://libtomcrypt.com
14 @file rsa_encrypt_key.c
15 RSA PKCS #1 encryption, Tom St Denis and Andreas Lange
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
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)
40 unsigned long modulus_bitlen, modulus_bytelen, x;
43 LTC_ARGCHK(in != NULL);
44 LTC_ARGCHK(out != NULL);
45 LTC_ARGCHK(outlen != NULL);
46 LTC_ARGCHK(key != NULL);
49 if ((padding != LTC_PKCS_1_V1_5) &&
50 (padding != LTC_PKCS_1_OAEP)) {
51 return CRYPT_PK_INVALID_PADDING;
55 if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
59 if (padding == LTC_PKCS_1_OAEP) {
61 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
66 /* get modulus len in bits */
67 modulus_bitlen = mp_count_bits( (key->N));
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;
76 if (padding == LTC_PKCS_1_OAEP) {
77 /* OAEP pad the key */
79 if ((err = pkcs_1_oaep_encode(in, inlen, lparam,
80 lparamlen, modulus_bitlen, prng, prng_idx, hash_idx,
81 out, &x)) != CRYPT_OK) {
85 /* PKCS #1 v1.5 pad the key */
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) {
94 /* rsa exptmod the OAEP or PKCS #1 v1.5 pad */
95 return ltc_mp.rsa_me(out, x, out, outlen, PK_PUBLIC, key);
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 $ */