47950d3b24557e0c89c93b7469b452b721614f1c
[silc.git] / lib / silccrypt / pkcs1.c
1 /* $Id$ */
2 /* 
3    PKCS #1 RSA wrapper.
4
5    Heavily modified to work under SILC, rewrote all interfaces, code that
6    is not needed in SILC has been removed for good, and some code was fixed
7    and changed.
8
9    For example, RSA_DecodeOneBlock was not used at all by Mozilla, however,
10    I took this code in to use after doing some fixing (it had some bugs).  
11    Also, OAEP is removed totally for now.  I'm not sure whether OAEP could
12    be used in the future with SILC but not for now.
13
14    This file also implements partial SILC PKCS API for RSA with PKCS #1.
15    It is partial because all the other functions but encrypt, decrypt,
16    sign and verify are common.
17
18    Note:
19
20    The mandatory PKCS #1 implementation in SILC must be compliant to either
21    PKCS #1 version 1.5 or PKCS #1 version 2 with the following notes:
22    The signature encoding is always in same format as the encryption
23    encoding regardles of the PKCS #1 version.  The signature with
24    appendix (with hash algorithm OID in the data) must not be used
25    in the SILC.  Rationale for this is that there is no binding between
26    the PKCS #1 OIDs and the hash algorithms used in the SILC protocol.
27    Hence, the encoding is always in PKCS #1 version 1.5 format.
28
29    Any questions and comments regarding this modified version should be
30    sent to priikone@poseidon.pspt.fi.
31
32    References: ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-1v2.asc,
33                ftp://ftp.rsasecurity.com/pub/pkcs/ascii/pkcs-1.asc,
34                and RFC 2437.
35
36    Copyright notice: All code in this file, including the SILC PKCS API
37    code that is not part of the Mozilla code, falls under the same license
38    (MPL or GPL) found attached to this file, below.
39 */
40
41 /*
42  * PKCS#1 encoding and decoding functions.
43  * This file is believed to contain no code licensed from other parties.
44  *
45  * The contents of this file are subject to the Mozilla Public
46  * License Version 1.1 (the "License"); you may not use this file
47  * except in compliance with the License. You may obtain a copy of
48  * the License at http://www.mozilla.org/MPL/
49  * 
50  * Software distributed under the License is distributed on an "AS
51  * IS" basis, WITHOUT WARRANTY OF ANY KIND, either express or
52  * implied. See the License for the specific language governing
53  * rights and limitations under the License.
54  * 
55  * The Original Code is the Netscape security libraries.
56  * 
57  * The Initial Developer of the Original Code is Netscape
58  * Communications Corporation.  Portions created by Netscape are 
59  * Copyright (C) 1994-2000 Netscape Communications Corporation.  All
60  * Rights Reserved.
61  * 
62  * Contributor(s):
63  * 
64  * Alternatively, the contents of this file may be used under the
65  * terms of the GNU General Public License Version 2 or later (the
66  * "GPL"), in which case the provisions of the GPL are applicable 
67  * instead of those above.  If you wish to allow use of your 
68  * version of this file only under the terms of the GPL and not to
69  * allow others to use your version of this file under the MPL,
70  * indicate your decision by deleting the provisions above and
71  * replace them with the notice and other provisions required by
72  * the GPL.  If you do not delete the provisions above, a recipient
73  * may use your version of this file under either the MPL or the
74  * GPL.
75  *
76  * $Id$
77  */
78
79 #include "silcincludes.h"
80 #include "rsa.h"
81
82 #define RSA_BLOCK_MIN_PAD_LEN           8
83 #define RSA_BLOCK_FIRST_OCTET           0x00
84 #define RSA_BLOCK_PRIVATE0_PAD_OCTET    0x00
85 #define RSA_BLOCK_PRIVATE_PAD_OCTET     0xff
86 #define RSA_BLOCK_AFTER_PAD_OCTET       0x00
87
88 /*
89  * RSA block types
90  *
91  * The actual values are important -- they are fixed, *not* arbitrary.
92  * The explicit value assignments are not needed (because C would give
93  * us those same values anyway) but are included as a reminder...
94  */
95 typedef enum {
96     RSA_BlockPrivate0 = 0,      /* unused, really */
97     RSA_BlockPrivate = 1,       /* pad for a private-key operation */
98     RSA_BlockPublic = 2,        /* pad for a public-key operation */
99     RSA_BlockTotal
100 } RSA_BlockType;
101
102 /*
103  * Format one block of data for public/private key encryption using
104  * the rules defined in PKCS #1.
105  */
106 static unsigned char *
107 RSA_FormatOneBlock(uint32 modulusLen, RSA_BlockType blockType,
108                    unsigned char *data, uint32 data_len)
109 {
110     unsigned char *block;
111     unsigned char *bp;
112     int padLen;
113     int i;
114
115     block = (unsigned char *) silc_malloc(modulusLen);
116     if (block == NULL)
117         return NULL;
118
119     bp = block;
120
121     /*
122      * All RSA blocks start with two octets:
123      *  0x00 || BlockType
124      */
125     *bp++ = RSA_BLOCK_FIRST_OCTET;
126     *bp++ = (unsigned char) blockType;
127
128     switch (blockType) {
129
130       /*
131        * Blocks intended for private-key operation.
132        */
133       case RSA_BlockPrivate0: /* essentially unused */
134       case RSA_BlockPrivate:     /* preferred method */
135         /*
136          * 0x00 || BT || Pad || 0x00 || ActualData
137          *   1      1   padLen    1      data_len
138          * Pad is either all 0x00 or all 0xff bytes, depending on blockType.
139          */
140         padLen = modulusLen - data_len - 3;
141         assert(padLen >= RSA_BLOCK_MIN_PAD_LEN);
142         memset(bp,
143                    blockType == RSA_BlockPrivate0
144                         ? RSA_BLOCK_PRIVATE0_PAD_OCTET
145                         : RSA_BLOCK_PRIVATE_PAD_OCTET,
146                    padLen);
147         bp += padLen;
148         *bp++ = RSA_BLOCK_AFTER_PAD_OCTET;
149         memcpy(bp, data, data_len);
150         break;
151
152       /*
153        * Blocks intended for public-key operation.
154        */
155       case RSA_BlockPublic:
156         /*
157          * 0x00 || BT || Pad || 0x00 || ActualData
158          *   1      1   padLen    1      data_len
159          * Pad is all non-zero random bytes.
160          */
161         padLen = modulusLen - data_len - 3;
162         assert(padLen >= RSA_BLOCK_MIN_PAD_LEN);
163         for (i = 0; i < padLen; i++) {
164             /* Pad with non-zero random data. */
165             do {
166                 silc_rng_global_get_byte(bp + i);
167             } while (bp[i] == RSA_BLOCK_AFTER_PAD_OCTET);
168         }
169         bp += padLen;
170         *bp++ = RSA_BLOCK_AFTER_PAD_OCTET;
171         memcpy(bp, data, data_len);
172         break;
173
174       default:
175         silc_free(block);
176         return NULL;
177     }
178
179     return block;
180 }
181
182 static int
183 RSA_FormatBlock(unsigned char **result, uint32 *result_len,
184                 uint32 modulusLen,
185                 RSA_BlockType blockType, unsigned char *data,
186                 uint32 data_len)
187 {
188     /*
189      * XXX For now assume that the data length fits in a single
190      * XXX encryption block; the ASSERTs below force this.
191      * XXX To fix it, each case will have to loop over chunks whose
192      * XXX lengths satisfy the assertions, until all data is handled.
193      * XXX (Unless RSA has more to say about how to handle data
194      * XXX which does not fit in a single encryption block?)
195      * XXX And I do not know what the result is supposed to be,
196      * XXX so the interface to this function may need to change
197      * XXX to allow for returning multiple blocks, if they are
198      * XXX not wanted simply concatenated one after the other.
199      */
200
201     switch (blockType) {
202       case RSA_BlockPrivate0:
203       case RSA_BlockPrivate:
204       case RSA_BlockPublic:
205         /*
206          * 0x00 || BT || Pad || 0x00 || ActualData
207          *
208          * The "3" below is the first octet + the second octet + the 0x00
209          * octet that always comes just before the ActualData.
210          */
211         assert(data_len <= (modulusLen - (3 + RSA_BLOCK_MIN_PAD_LEN)));
212
213         *result = RSA_FormatOneBlock(modulusLen, blockType, data, data_len);
214         if (result == NULL) {
215             *result_len = 0;
216             return FALSE;
217         }
218         *result_len = modulusLen;
219
220         break;
221
222       default:
223         *result = NULL;
224         *result_len = 0;
225         return FALSE;
226     }
227
228     return TRUE;
229 }
230
231 /*
232  * Takes a formatted block and returns the data part.
233  * (This is the inverse of RSA_FormatOneBlock().)
234  * In some formats the start of the data is ambiguous;
235  * if it is non-zero, expectedLen will disambiguate.
236  *
237  */
238 unsigned char *
239 RSA_DecodeOneBlock(unsigned char *data,
240                    uint32 modulusLen,
241                    uint32 expectedLen,
242                    RSA_BlockType bt,
243                    uint32 *pResultLen)
244 {
245     RSA_BlockType blockType;
246     unsigned char *dp, *res;
247     uint32 i, len = 0;
248
249     dp = data;
250     if (dp[0] != RSA_BLOCK_FIRST_OCTET) {
251         return NULL;
252     }
253
254     blockType = (RSA_BlockType)dp[1];
255     if (blockType != bt)
256       return NULL;
257
258     dp += 2;
259
260     switch (blockType) {
261       case RSA_BlockPrivate0:
262         /* Ignored */
263         res = (unsigned char *) silc_malloc(modulusLen);
264         memcpy(res, data, modulusLen);
265         break;
266
267       case RSA_BlockPrivate:
268         for (i = 0; i < modulusLen; i++) {
269             if (*dp++ != RSA_BLOCK_PRIVATE_PAD_OCTET)
270                 break;
271         }
272         if (i == modulusLen)
273             return NULL;
274         len = modulusLen - (dp - data);
275         res = (unsigned char *) silc_malloc(len);
276         if (res == NULL) {
277             return NULL;
278         }
279         memcpy(res, dp, len);
280         break;
281
282       case RSA_BlockPublic:
283         for (i = 0; i < modulusLen; i++) {
284             if (*dp++ == RSA_BLOCK_AFTER_PAD_OCTET)
285                 break;
286         }
287         if (i == modulusLen)
288             return NULL;
289         len = modulusLen - (dp - data);
290         res = (unsigned char *) silc_malloc(len);
291         if (res == NULL) {
292             return NULL;
293         }
294         memcpy(res, dp, len);
295         break;
296
297       default:
298         return NULL;
299     }
300
301     if (pResultLen)
302       *pResultLen = len;
303     return res;
304 }
305
306 /*
307  * SILC PKCS API for PKCS #1
308  *
309  * Note all the other PKCS API functions are used from the rsa.c.
310  * See the definitions in rsa.c and in silcpkcs.c.
311  */
312
313 SILC_PKCS_API_ENCRYPT(pkcs1)
314 {
315   RsaKey *key = (RsaKey *)context;
316   SilcMPInt mp_tmp;
317   SilcMPInt mp_dst;
318   unsigned char *padded;
319   uint32 padded_len, len = key->bits / 8;
320
321   /* Pad data */
322   if (!RSA_FormatBlock(&padded, &padded_len, len,
323                        RSA_BlockPublic, src, src_len))
324     return FALSE;
325
326   silc_mp_init(&mp_tmp);
327   silc_mp_init(&mp_dst);
328   silc_mp_set_ui(&mp_tmp, 0);
329   silc_mp_set_ui(&mp_dst, 0);
330
331   /* Data to MP */
332   silc_mp_bin2mp(padded, padded_len, &mp_tmp);
333
334   /* Encrypt */
335   rsa_en_de_crypt(&mp_dst, &mp_tmp, &key->e, &key->n);
336   
337   /* MP to data */
338   silc_mp_mp2bin_noalloc(&mp_dst, dst, len);
339   *dst_len = len;
340
341   memset(padded, 0, padded_len);
342   silc_free(padded);
343   silc_mp_uninit(&mp_tmp);
344   silc_mp_uninit(&mp_dst);
345
346   return TRUE;
347 }
348
349 SILC_PKCS_API_DECRYPT(pkcs1)
350 {
351   RsaKey *key = (RsaKey *)context;
352   SilcMPInt mp_tmp;
353   SilcMPInt mp_dst;
354   unsigned char *padded, *unpadded;
355   uint32 padded_len;
356
357   silc_mp_init(&mp_tmp);
358   silc_mp_init(&mp_dst);
359   silc_mp_set_ui(&mp_tmp, 0);
360   silc_mp_set_ui(&mp_dst, 0);
361
362   /* Data to MP */
363   silc_mp_bin2mp(src, src_len, &mp_tmp);
364
365   /* Decrypt */
366   rsa_en_de_crypt(&mp_dst, &mp_tmp, &key->d, &key->n);
367
368   /* MP to data */
369   padded = silc_mp_mp2bin(&mp_dst, key->bits / 8, &padded_len);
370
371   /* Unpad data */
372   unpadded = RSA_DecodeOneBlock(padded, padded_len, 0, 
373                                 RSA_BlockPublic, &padded_len);
374   if (!unpadded) {
375     memset(padded, 0, padded_len);
376     silc_free(padded);
377     silc_mp_uninit(&mp_tmp);
378     silc_mp_uninit(&mp_dst);
379     return FALSE;
380   }
381
382   /* Copy to destination */
383   memcpy(dst, unpadded, padded_len);
384   *dst_len = padded_len;
385
386   memset(padded, 0, padded_len);
387   memset(unpadded, 0, padded_len);
388   silc_free(padded);
389   silc_free(unpadded);
390   silc_mp_uninit(&mp_tmp);
391   silc_mp_uninit(&mp_dst);
392
393   return TRUE;
394 }
395
396 SILC_PKCS_API_SIGN(pkcs1)
397 {
398   RsaKey *key = (RsaKey *)context;
399   SilcMPInt mp_tmp;
400   SilcMPInt mp_dst;
401   unsigned char *padded;
402   uint32 padded_len;
403   uint32 len = key->bits / 8;
404
405   /* Pad data */
406   if (!RSA_FormatBlock(&padded, &padded_len, len, RSA_BlockPrivate, 
407                        src, src_len))
408     return FALSE;
409
410   silc_mp_init(&mp_tmp);
411   silc_mp_init(&mp_dst);
412   silc_mp_set_ui(&mp_tmp, 0);
413   silc_mp_set_ui(&mp_dst, 0);
414
415   /* Data to MP */
416   silc_mp_bin2mp(padded, len, &mp_tmp);
417
418   /* Sign */
419   rsa_en_de_crypt(&mp_dst, &mp_tmp, &key->d, &key->n);
420   
421   /* MP to data */
422   silc_mp_mp2bin_noalloc(&mp_dst, dst, len);
423   *dst_len = len;
424
425   memset(padded, 0, padded_len);
426   silc_free(padded);
427   silc_mp_uninit(&mp_tmp);
428   silc_mp_uninit(&mp_dst);
429
430   return TRUE;
431 }
432
433 SILC_PKCS_API_VERIFY(pkcs1)
434 {
435   RsaKey *key = (RsaKey *)context;
436   int ret = TRUE;
437   SilcMPInt mp_tmp2;
438   SilcMPInt mp_dst;
439   unsigned char *verify, *unpadded;
440   uint32 verify_len, len = key->bits / 8;
441
442   silc_mp_init(&mp_tmp2);
443   silc_mp_init(&mp_dst);
444   silc_mp_set_ui(&mp_tmp2, 0);
445   silc_mp_set_ui(&mp_dst, 0);
446
447   /* Format the signature into MP int */
448   silc_mp_bin2mp(signature, signature_len, &mp_tmp2);
449
450   /* Verify */
451   rsa_en_de_crypt(&mp_dst, &mp_tmp2, &key->e, &key->n);
452
453   /* MP to data */
454   verify = silc_mp_mp2bin(&mp_dst, len, &verify_len);
455
456   /* Unpad data */
457   unpadded = RSA_DecodeOneBlock(verify, len, 0, 
458                                 RSA_BlockPrivate, &verify_len);
459   if (!unpadded) {
460     memset(verify, 0, verify_len);
461     silc_free(verify);
462     silc_mp_uninit(&mp_tmp2);
463     silc_mp_uninit(&mp_dst);
464     return FALSE;
465   }
466
467   /* Compare */
468   if (memcmp(data, unpadded, verify_len))
469     ret = FALSE;
470
471   memset(verify, 0, verify_len);
472   memset(unpadded, 0, verify_len);
473   silc_free(verify);
474   silc_free(unpadded);
475   silc_mp_uninit(&mp_tmp2);
476   silc_mp_uninit(&mp_dst);
477
478   return ret;
479 }