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
12 @file rsa_encrypt_key.c
13 RSA PKCS #1 encryption, Tom St Denis and Andreas Lange
19 (PKCS #1 v2.0) OAEP pad then encrypt
20 @param in The plaintext
21 @param inlen The length of the plaintext (octets)
22 @param out [out] The ciphertext
23 @param outlen [in/out] The max size and resulting size of the ciphertext
24 @param lparam The system "lparam" for the encryption
25 @param lparamlen The length of lparam (octets)
26 @param prng An active PRNG
27 @param prng_idx The index of the desired prng
28 @param hash_idx The index of the desired hash
29 @param padding Type of padding (LTC_PKCS_1_OAEP or LTC_PKCS_1_V1_5)
30 @param key The RSA key to encrypt to
31 @return CRYPT_OK if successful
33 int rsa_encrypt_key_ex(const unsigned char *in, unsigned long inlen,
34 unsigned char *out, unsigned long *outlen,
35 const unsigned char *lparam, unsigned long lparamlen,
36 prng_state *prng, int prng_idx, int hash_idx, int padding, rsa_key *key)
38 unsigned long modulus_bitlen, modulus_bytelen, x;
41 LTC_ARGCHK(in != NULL);
42 LTC_ARGCHK(out != NULL);
43 LTC_ARGCHK(outlen != NULL);
44 LTC_ARGCHK(key != NULL);
47 if ((padding != LTC_PKCS_1_V1_5) &&
48 (padding != LTC_PKCS_1_OAEP)) {
49 return CRYPT_PK_INVALID_PADDING;
53 if ((err = prng_is_valid(prng_idx)) != CRYPT_OK) {
57 if (padding == LTC_PKCS_1_OAEP) {
59 if ((err = hash_is_valid(hash_idx)) != CRYPT_OK) {
64 /* get modulus len in bits */
65 modulus_bitlen = mp_count_bits( (key->N));
67 /* outlen must be at least the size of the modulus */
68 modulus_bytelen = mp_unsigned_bin_size( (key->N));
69 if (modulus_bytelen > *outlen) {
70 *outlen = modulus_bytelen;
71 return CRYPT_BUFFER_OVERFLOW;
74 if (padding == LTC_PKCS_1_OAEP) {
75 /* OAEP pad the key */
77 if ((err = pkcs_1_oaep_encode(in, inlen, lparam,
78 lparamlen, modulus_bitlen, prng, prng_idx, hash_idx,
79 out, &x)) != CRYPT_OK) {
83 /* PKCS #1 v1.5 pad the key */
85 if ((err = pkcs_1_v1_5_encode(in, inlen, LTC_PKCS_1_EME,
86 modulus_bitlen, prng, prng_idx,
87 out, &x)) != CRYPT_OK) {
92 /* rsa exptmod the OAEP or PKCS #1 v1.5 pad */
93 return ltc_mp.rsa_me(out, x, out, outlen, PK_PUBLIC, key);
98 /* ref: $Format:%D$ */
99 /* git commit: $Format:%H$ */
100 /* commit time: $Format:%ai$ */