1 /* LibTomCrypt, modular cryptographic library -- Tom St Denis */
2 /* SPDX-License-Identifier: Unlicense */
3 #include "tomcrypt_private.h"
4
5 /*! \file pkcs_1_v1_5_encode.c
6 *
7 * PKCS #1 v1.5 Padding (Andreas Lange)
8 */
9
10 #ifdef LTC_PKCS_1
11
12 /*! \brief PKCS #1 v1.5 encode.
13 *
14 * \param msg The data to encode
15 * \param msglen The length of the data to encode (octets)
16 * \param block_type Block type to use in padding (\sa ltc_pkcs_1_v1_5_blocks)
17 * \param modulus_bitlen The bit length of the RSA modulus
18 * \param prng An active PRNG state (only for LTC_PKCS_1_EME)
19 * \param prng_idx The index of the PRNG desired (only for LTC_PKCS_1_EME)
20 * \param out [out] The destination for the encoded data
21 * \param outlen [in/out] The max size and resulting size of the encoded data
22 *
23 * \return CRYPT_OK if successful
24 */
pkcs_1_v1_5_encode(const unsigned char * msg,unsigned long msglen,int block_type,unsigned long modulus_bitlen,prng_state * prng,int prng_idx,unsigned char * out,unsigned long * outlen)25 int pkcs_1_v1_5_encode(const unsigned char *msg,
26 unsigned long msglen,
27 int block_type,
28 unsigned long modulus_bitlen,
29 prng_state *prng,
30 int prng_idx,
31 unsigned char *out,
32 unsigned long *outlen)
33 {
34 unsigned long modulus_len, ps_len, i;
35 unsigned char *ps;
36 int result;
37
38 /* valid block_type? */
39 if ((block_type != LTC_PKCS_1_EMSA) &&
40 (block_type != LTC_PKCS_1_EME)) {
41 return CRYPT_PK_INVALID_PADDING;
42 }
43
44 if (block_type == LTC_PKCS_1_EME) { /* encryption padding, we need a valid PRNG */
45 if ((result = prng_is_valid(prng_idx)) != CRYPT_OK) {
46 return result;
47 }
48 }
49
50 modulus_len = (modulus_bitlen >> 3) + (modulus_bitlen & 7 ? 1 : 0);
51
52 /* test message size */
53 if ((msglen + 11) > modulus_len) {
54 return CRYPT_PK_INVALID_SIZE;
55 }
56
57 if (*outlen < modulus_len) {
58 *outlen = modulus_len;
59 result = CRYPT_BUFFER_OVERFLOW;
60 goto bail;
61 }
62
63 /* generate an octets string PS */
64 ps = &out[2];
65 ps_len = modulus_len - msglen - 3;
66
67 if (block_type == LTC_PKCS_1_EME) {
68 /* now choose a random ps */
69 if (prng_descriptor[prng_idx]->read(ps, ps_len, prng) != ps_len) {
70 result = CRYPT_ERROR_READPRNG;
71 goto bail;
72 }
73
74 /* transform zero bytes (if any) to non-zero random bytes */
75 for (i = 0; i < ps_len; i++) {
76 while (ps[i] == 0) {
77 if (prng_descriptor[prng_idx]->read(&ps[i], 1, prng) != 1) {
78 result = CRYPT_ERROR_READPRNG;
79 goto bail;
80 }
81 }
82 }
83 } else {
84 XMEMSET(ps, 0xFF, ps_len);
85 }
86
87 /* create string of length modulus_len */
88 out[0] = 0x00;
89 out[1] = (unsigned char)block_type; /* block_type 1 or 2 */
90 out[2 + ps_len] = 0x00;
91 XMEMCPY(&out[2 + ps_len + 1], msg, msglen);
92 *outlen = modulus_len;
93
94 result = CRYPT_OK;
95 bail:
96 return result;
97 } /* pkcs_1_v1_5_encode */
98
99 #endif /* #ifdef LTC_PKCS_1 */
100