cfb8: Fix decrypt path
[gd/nettle] / pkcs1-encrypt.c
1 /* pkcs1-encrypt.c
2
3    The RSA publickey algorithm. PKCS#1 encryption.
4
5    Copyright (C) 2001, 2012 Niels Möller
6
7    This file is part of GNU Nettle.
8
9    GNU Nettle is free software: you can redistribute it and/or
10    modify it under the terms of either:
11
12      * the GNU Lesser General Public License as published by the Free
13        Software Foundation; either version 3 of the License, or (at your
14        option) any later version.
15
16    or
17
18      * the GNU General Public License as published by the Free
19        Software Foundation; either version 2 of the License, or (at your
20        option) any later version.
21
22    or both in parallel, as here.
23
24    GNU Nettle is distributed in the hope that it will be useful,
25    but WITHOUT ANY WARRANTY; without even the implied warranty of
26    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
27    General Public License for more details.
28
29    You should have received copies of the GNU General Public License and
30    the GNU Lesser General Public License along with this program.  If
31    not, see http://www.gnu.org/licenses/.
32 */
33
34 #if HAVE_CONFIG_H
35 # include "config.h"
36 #endif
37
38 #include <assert.h>
39 #include <stdlib.h>
40 #include <string.h>
41
42 #include "pkcs1.h"
43
44 #include "bignum.h"
45 #include "gmp-glue.h"
46
47 int
48 pkcs1_encrypt (size_t key_size,
49                /* For padding */
50                void *random_ctx, nettle_random_func *random,
51                size_t length, const uint8_t *message,
52                mpz_t m)
53 {
54   TMP_GMP_DECL(em, uint8_t);
55   size_t padding;
56   size_t i;
57
58   /* The message is encoded as a string of the same length as the
59    * modulo n, of the form
60    *
61    *   00 02 pad 00 message
62    *
63    * where padding should be at least 8 pseudorandomly generated
64    * *non-zero* octets. */
65      
66   if (length + 11 > key_size)
67     /* Message too long for this key. */
68     return 0;
69
70   /* At least 8 octets of random padding */
71   padding = key_size - length - 3;
72   assert(padding >= 8);
73   
74   TMP_GMP_ALLOC(em, key_size - 1);
75   em[0] = 2;
76
77   random(random_ctx, padding, em + 1);
78
79   /* Replace 0-octets with 1 */
80   for (i = 0; i<padding; i++)
81     if (!em[i+1])
82       em[i+1] = 1;
83
84   em[padding+1] = 0;
85   memcpy(em + padding + 2, message, length);
86
87   nettle_mpz_set_str_256_u(m, key_size - 1, em);
88
89   TMP_GMP_FREE(em);
90   return 1;
91 }