Added preliminary Symbian support.
[silc.git] / lib / silccrypt / silcpkcs1.c
1 /*
2
3   silcpkcs1.c
4
5   Author: Pekka Riikonen <priikone@silcnet.org>
6
7   Copyright (C) 2003 - 2007 Pekka Riikonen
8
9   This program is free software; you can redistribute it and/or modify
10   it under the terms of the GNU General Public License as published by
11   the Free Software Foundation; version 2 of the License.
12
13   This program is distributed in the hope that it will be useful,
14   but WITHOUT ANY WARRANTY; without even the implied warranty of
15   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
16   GNU General Public License for more details.
17
18 */
19 /* $Id$ */
20
21 #include "silc.h"
22 #include "rsa.h"
23
24 /************************** PKCS #1 message format ***************************/
25
26 /* Minimum padding in block */
27 #define SILC_PKCS1_MIN_PADDING 8
28
29 /* Encodes PKCS#1 data block from the `data' according to the block type
30    indicated by `bt'.  When encoding signatures the `bt' must be
31    SILC_PKCS1_BT_PRV1 and when encoding encryption blocks the `bt' must
32    be SILC_PKCS1_BT_PUB.  The encoded data is copied into the `dest_data'
33    buffer which is size of `dest_data_size'.  If the `dest_data' is not
34    able to hold the encoded block this returns FALSE.  The `rng' must be
35    set when `bt' is SILC_PKCS1_BT_PUB.  This function returns TRUE on
36    success. */
37
38 SilcBool silc_pkcs1_encode(SilcPkcs1BlockType bt,
39                            const unsigned char *data,
40                            SilcUInt32 data_len,
41                            unsigned char *dest_data,
42                            SilcUInt32 dest_data_size,
43                            SilcRng rng)
44 {
45   SilcInt32 padlen;
46   int i;
47
48   SILC_LOG_DEBUG(("PKCS#1 encoding, bt %d", bt));
49
50   if (!data || !dest_data ||
51       dest_data_size < SILC_PKCS1_MIN_PADDING + 3 ||
52       dest_data_size < data_len) {
53     SILC_LOG_DEBUG(("Data to be encoded is too long"));
54     return FALSE;
55   }
56
57   /* Start of block */
58   dest_data[0] = 0x00;
59   dest_data[1] = (unsigned char)bt;
60
61   padlen = (SilcInt32)dest_data_size - (SilcInt32)data_len - 3;
62   if (padlen < SILC_PKCS1_MIN_PADDING) {
63     SILC_LOG_DEBUG(("Data to be encoded is too long"));
64     return FALSE;
65   }
66
67   /* Encode according to block type */
68   switch (bt) {
69   case SILC_PKCS1_BT_PRV0:
70   case SILC_PKCS1_BT_PRV1:
71     /* Signature */
72     memset(dest_data + 2, bt == SILC_PKCS1_BT_PRV1 ? 0xff : 0x00, padlen);
73     break;
74
75   case SILC_PKCS1_BT_PUB:
76     /* Encryption */
77     if (!rng) {
78       SILC_LOG_ERROR(("Cannot encrypt: random number generator not provided"));
79       return FALSE;
80     }
81
82     /* It is guaranteed this routine does not return zero byte. */
83     for (i = 2; i < padlen; i++)
84       dest_data[i] = silc_rng_get_byte_fast(rng);
85
86     break;
87   }
88
89   /* Copy the data */
90   dest_data[padlen + 2] = 0x00;
91   memcpy(dest_data + padlen + 3, data, data_len);
92
93   return TRUE;
94 }
95
96 /* Decodes the PKCS#1 encoded block according to the block type `bt'.
97    When verifying signatures the `bt' must be SILC_PKCS1_BT_PRV1 and
98    when decrypting it must be SILC_PKCS1_BT_PUB.  This copies the
99    decoded data into `dest_data' which is size of `dest_data_size'.  If
100    the deocded block does not fit to `dest_data' this returns FALSE.
101    Returns TRUE on success. */
102
103 SilcBool silc_pkcs1_decode(SilcPkcs1BlockType bt,
104                            const unsigned char *data,
105                            SilcUInt32 data_len,
106                            unsigned char *dest_data,
107                            SilcUInt32 dest_data_size,
108                            SilcUInt32 *dest_len)
109 {
110   int i = 0;
111
112   SILC_LOG_DEBUG(("PKCS#1 decoding, bt %d", bt));
113
114   /* Sanity checks */
115   if (!data || !dest_data || dest_data_size < 3 ||
116       data[0] != 0x00 || data[1] != (unsigned char)bt) {
117     SILC_LOG_DEBUG(("Malformed block"));
118     return FALSE;
119   }
120
121   /* Decode according to block type */
122   switch (bt) {
123   case SILC_PKCS1_BT_PRV0:
124     /* Do nothing */
125     break;
126
127   case SILC_PKCS1_BT_PRV1:
128     /* Verification */
129     for (i = 2; i < data_len; i++)
130       if (data[i] != 0xff)
131         break;
132     break;
133
134   case SILC_PKCS1_BT_PUB:
135     /* Decryption */
136     for (i = 2; i < data_len; i++)
137       if (data[i] == 0x00)
138         break;
139     break;
140   }
141
142   /* Sanity checks */
143   if (data[i++] != 0x00) {
144     SILC_LOG_DEBUG(("Malformed block"));
145     return FALSE;
146   }
147   if (i - 1 < SILC_PKCS1_MIN_PADDING) {
148     SILC_LOG_DEBUG(("Malformed block"));
149     return FALSE;
150   }
151   if (dest_data_size < data_len - i) {
152     SILC_LOG_DEBUG(("Destination buffer too small"));
153     return FALSE;
154   }
155
156   /* Copy the data */
157   memcpy(dest_data, data + i, data_len - i);
158
159   /* Return data length */
160   if (dest_len)
161     *dest_len = data_len - i;
162
163   return TRUE;
164 }
165
166
167 /***************************** PKCS #1 PKCS API ******************************/
168
169 /* Generates RSA key pair. */
170
171 SilcBool silc_pkcs1_generate_key(SilcUInt32 keylen,
172                                  SilcRng rng,
173                                  void **ret_public_key,
174                                  void **ret_private_key)
175 {
176   SilcUInt32 prime_bits = keylen / 2;
177   SilcMPInt p, q;
178   SilcBool found = FALSE;
179
180   if (keylen < 768 || keylen > 16384)
181     return FALSE;
182
183   silc_mp_init(&p);
184   silc_mp_init(&q);
185
186   /* Find p and q */
187   while (!found) {
188     silc_math_gen_prime(&p, prime_bits, FALSE, rng);
189     silc_math_gen_prime(&q, prime_bits, FALSE, rng);
190     if ((silc_mp_cmp(&p, &q)) != 0)
191       found = TRUE;
192   }
193
194   /* If p is smaller than q, switch them */
195   if ((silc_mp_cmp(&p, &q)) > 0) {
196     SilcMPInt hlp;
197     silc_mp_init(&hlp);
198
199     silc_mp_set(&hlp, &p);
200     silc_mp_set(&p, &q);
201     silc_mp_set(&q, &hlp);
202
203     silc_mp_uninit(&hlp);
204   }
205
206   /* Generate the actual keys */
207   if (!rsa_generate_keys(keylen, &p, &q, ret_public_key, ret_private_key))
208     return FALSE;
209
210   silc_mp_uninit(&p);
211   silc_mp_uninit(&q);
212
213   return TRUE;
214 }
215
216 /* Import PKCS #1 compliant public key */
217
218 SilcBool silc_pkcs1_import_public_key(unsigned char *key,
219                                       SilcUInt32 key_len,
220                                       void **ret_public_key)
221 {
222   SilcAsn1 asn1 = NULL;
223   SilcBufferStruct alg_key;
224   RsaPublicKey *pubkey;
225
226   if (!ret_public_key)
227     return FALSE;
228
229   asn1 = silc_asn1_alloc();
230   if (!asn1)
231     return FALSE;
232
233   /* Allocate RSA public key */
234   *ret_public_key = pubkey = silc_calloc(1, sizeof(*pubkey));
235   if (!pubkey)
236     goto err;
237
238   /* Parse the PKCS #1 public key */
239   silc_buffer_set(&alg_key, key, key_len);
240   if (!silc_asn1_decode(asn1, &alg_key,
241                         SILC_ASN1_OPTS(SILC_ASN1_ALLOC),
242                         SILC_ASN1_SEQUENCE,
243                           SILC_ASN1_INT(&pubkey->n),
244                           SILC_ASN1_INT(&pubkey->e),
245                         SILC_ASN1_END, SILC_ASN1_END))
246     goto err;
247
248   /* Set key length */
249   pubkey->bits = silc_mp_sizeinbase(&pubkey->n, 2);
250
251   silc_asn1_free(asn1);
252
253   return TRUE;
254
255  err:
256   silc_asn1_free(asn1);
257   return FALSE;
258 }
259
260 /* Export PKCS #1 compliant public key */
261
262 unsigned char *silc_pkcs1_export_public_key(void *public_key,
263                                             SilcUInt32 *ret_len)
264 {
265   RsaPublicKey *key = public_key;
266   SilcAsn1 asn1 = NULL;
267   SilcBufferStruct alg_key;
268   unsigned char *ret;
269
270   asn1 = silc_asn1_alloc();
271   if (!asn1)
272     goto err;
273
274   /* Encode to PKCS #1 public key */
275   memset(&alg_key, 0, sizeof(alg_key));
276   if (!silc_asn1_encode(asn1, &alg_key,
277                         SILC_ASN1_OPTS(SILC_ASN1_ALLOC),
278                         SILC_ASN1_SEQUENCE,
279                           SILC_ASN1_INT(&key->n),
280                           SILC_ASN1_INT(&key->e),
281                         SILC_ASN1_END, SILC_ASN1_END))
282     goto err;
283
284   ret = silc_buffer_steal(&alg_key, ret_len);
285   silc_asn1_free(asn1);
286
287   return ret;
288
289  err:
290   if (asn1)
291     silc_asn1_free(asn1);
292   return NULL;
293 }
294
295 /* Returns key length */
296
297 SilcUInt32 silc_pkcs1_public_key_bitlen(void *public_key)
298 {
299   RsaPublicKey *key = public_key;
300   return key->bits;
301 }
302
303 /* Copy public key */
304
305 void *silc_pkcs1_public_key_copy(void *public_key)
306 {
307   RsaPublicKey *key = public_key, *new_key;
308
309   new_key = silc_calloc(1, sizeof(*new_key));
310   if (!new_key)
311     return NULL;
312
313   silc_mp_init(&new_key->n);
314   silc_mp_init(&new_key->e);
315   silc_mp_set(&new_key->n, &key->n);
316   silc_mp_set(&new_key->e, &key->e);
317   new_key->bits = key->bits;
318
319   return new_key;
320 }
321
322 /* Compare public keys */
323
324 SilcBool silc_pkcs1_public_key_compare(void *key1, void *key2)
325 {
326   RsaPublicKey *k1 = key1, *k2 = key2;
327
328   if (k1->bits != k2->bits)
329     return FALSE;
330   if (silc_mp_cmp(&k1->e, &k2->e) != 0)
331     return FALSE;
332   if (silc_mp_cmp(&k1->n, &k2->n) != 0)
333     return FALSE;
334
335   return TRUE;
336 }
337
338 /* Frees public key */
339
340 void silc_pkcs1_public_key_free(void *public_key)
341 {
342   RsaPublicKey *key = public_key;
343
344   silc_mp_uninit(&key->n);
345   silc_mp_uninit(&key->e);
346   silc_free(key);
347 }
348
349 /* Import PKCS #1 compliant private key */
350
351 SilcBool silc_pkcs1_import_private_key(unsigned char *key,
352                                        SilcUInt32 key_len,
353                                        void **ret_private_key)
354 {
355   SilcAsn1 asn1;
356   SilcBufferStruct alg_key;
357   RsaPrivateKey *privkey;
358   SilcUInt32 ver;
359
360   if (!ret_private_key)
361     return FALSE;
362
363   asn1 = silc_asn1_alloc();
364   if (!asn1)
365     return FALSE;
366
367   /* Allocate RSA private key */
368   *ret_private_key = privkey = silc_calloc(1, sizeof(*privkey));
369   if (!privkey)
370     goto err;
371
372   /* Parse the PKCS #1 private key */
373   silc_buffer_set(&alg_key, key, key_len);
374   if (!silc_asn1_decode(asn1, &alg_key,
375                         SILC_ASN1_OPTS(SILC_ASN1_ALLOC),
376                         SILC_ASN1_SEQUENCE,
377                           SILC_ASN1_SHORT_INT(&ver),
378                           SILC_ASN1_INT(&privkey->n),
379                           SILC_ASN1_INT(&privkey->e),
380                           SILC_ASN1_INT(&privkey->d),
381                           SILC_ASN1_INT(&privkey->p),
382                           SILC_ASN1_INT(&privkey->q),
383                           SILC_ASN1_INT(&privkey->dP),
384                           SILC_ASN1_INT(&privkey->dQ),
385                           SILC_ASN1_INT(&privkey->qP),
386                         SILC_ASN1_END, SILC_ASN1_END))
387     goto err;
388
389   if (ver != 0)
390     goto err;
391
392   /* Set key length */
393   privkey->bits = silc_mp_sizeinbase(&privkey->n, 2);
394
395   silc_asn1_free(asn1);
396
397   return TRUE;
398
399  err:
400   silc_asn1_free(asn1);
401   return FALSE;
402 }
403
404 /* Export PKCS #1 compliant private key */
405
406 unsigned char *silc_pkcs1_export_private_key(void *private_key,
407                                              SilcUInt32 *ret_len)
408 {
409   RsaPrivateKey *key = private_key;
410   SilcAsn1 asn1;
411   SilcBufferStruct alg_key;
412   unsigned char *ret;
413
414   asn1 = silc_asn1_alloc();
415   if (!asn1)
416     return FALSE;
417
418   /* Encode to PKCS #1 private key */
419   memset(&alg_key, 0, sizeof(alg_key));
420   if (!silc_asn1_encode(asn1, &alg_key,
421                         SILC_ASN1_OPTS(SILC_ASN1_ALLOC),
422                         SILC_ASN1_SEQUENCE,
423                           SILC_ASN1_SHORT_INT(0),
424                           SILC_ASN1_INT(&key->n),
425                           SILC_ASN1_INT(&key->e),
426                           SILC_ASN1_INT(&key->d),
427                           SILC_ASN1_INT(&key->p),
428                           SILC_ASN1_INT(&key->q),
429                           SILC_ASN1_INT(&key->dP),
430                           SILC_ASN1_INT(&key->dQ),
431                           SILC_ASN1_INT(&key->qP),
432                         SILC_ASN1_END, SILC_ASN1_END))
433     goto err;
434
435   ret = silc_buffer_steal(&alg_key, ret_len);
436   silc_asn1_free(asn1);
437
438   return ret;
439
440  err:
441   silc_asn1_free(asn1);
442   return NULL;
443 }
444
445 /* Returns key length */
446
447 SilcUInt32 silc_pkcs1_private_key_bitlen(void *private_key)
448 {
449   RsaPrivateKey *key = private_key;
450   return key->bits;
451 }
452
453 /* Frees private key */
454
455 void silc_pkcs1_private_key_free(void *private_key)
456 {
457   RsaPrivateKey *key = private_key;
458
459   silc_mp_uninit(&key->n);
460   silc_mp_uninit(&key->e);
461   silc_mp_uninit(&key->d);
462   silc_mp_uninit(&key->dP);
463   silc_mp_uninit(&key->dQ);
464   silc_mp_uninit(&key->qP);
465   silc_mp_uninit(&key->p);
466   silc_mp_uninit(&key->q);
467   silc_free(key);
468 }
469
470 /* PKCS #1 RSA routines */
471
472 SilcBool silc_pkcs1_encrypt(void *public_key,
473                             unsigned char *src,
474                             SilcUInt32 src_len,
475                             unsigned char *dst,
476                             SilcUInt32 dst_size,
477                             SilcUInt32 *ret_dst_len,
478                             SilcRng rng)
479 {
480   RsaPublicKey *key = public_key;
481   SilcMPInt mp_tmp;
482   SilcMPInt mp_dst;
483   unsigned char padded[2048 + 1];
484   SilcUInt32 len = (key->bits + 7) / 8;
485
486   if (sizeof(padded) < len)
487     return FALSE;
488   if (dst_size < len)
489     return FALSE;
490
491   /* Pad data */
492   if (!silc_pkcs1_encode(SILC_PKCS1_BT_PUB, src, src_len,
493                          padded, len, rng))
494     return FALSE;
495
496   silc_mp_init(&mp_tmp);
497   silc_mp_init(&mp_dst);
498
499   /* Data to MP */
500   silc_mp_bin2mp(padded, len, &mp_tmp);
501
502   /* Encrypt */
503   rsa_public_operation(key, &mp_tmp, &mp_dst);
504
505   /* MP to data */
506   silc_mp_mp2bin_noalloc(&mp_dst, dst, len);
507   *ret_dst_len = len;
508
509   memset(padded, 0, sizeof(padded));
510   silc_mp_uninit(&mp_tmp);
511   silc_mp_uninit(&mp_dst);
512
513   return TRUE;
514 }
515
516 SilcBool silc_pkcs1_decrypt(void *private_key,
517                             unsigned char *src,
518                             SilcUInt32 src_len,
519                             unsigned char *dst,
520                             SilcUInt32 dst_size,
521                             SilcUInt32 *ret_dst_len)
522 {
523   RsaPrivateKey *key = private_key;
524   SilcMPInt mp_tmp;
525   SilcMPInt mp_dst;
526   unsigned char *padded, unpadded[2048 + 1];
527   SilcUInt32 padded_len;
528
529   if (dst_size < (key->bits + 7) / 8)
530     return FALSE;
531
532   silc_mp_init(&mp_tmp);
533   silc_mp_init(&mp_dst);
534
535   /* Data to MP */
536   silc_mp_bin2mp(src, src_len, &mp_tmp);
537
538   /* Decrypt */
539   rsa_private_operation(key, &mp_tmp, &mp_dst);
540
541   /* MP to data */
542   padded = silc_mp_mp2bin(&mp_dst, (key->bits + 7) / 8, &padded_len);
543
544   /* Unpad data */
545   if (!silc_pkcs1_decode(SILC_PKCS1_BT_PUB, padded, padded_len,
546                          unpadded, sizeof(unpadded), ret_dst_len)) {
547     memset(padded, 0, padded_len);
548     silc_free(padded);
549     silc_mp_uninit(&mp_tmp);
550     silc_mp_uninit(&mp_dst);
551     return FALSE;
552   }
553
554   /* Copy to destination */
555   memcpy(dst, unpadded, *ret_dst_len);
556
557   memset(padded, 0, padded_len);
558   memset(unpadded, 0, sizeof(unpadded));
559   silc_free(padded);
560   silc_mp_uninit(&mp_tmp);
561   silc_mp_uninit(&mp_dst);
562
563   return TRUE;
564 }
565
566 SilcBool silc_pkcs1_sign(void *private_key,
567                          unsigned char *src,
568                          SilcUInt32 src_len,
569                          unsigned char *signature,
570                          SilcUInt32 signature_size,
571                          SilcUInt32 *ret_signature_len,
572                          SilcHash hash)
573 {
574   return FALSE;
575 }
576
577 SilcBool silc_pkcs1_verify(void *public_key,
578                            unsigned char *signature,
579                            SilcUInt32 signature_len,
580                            unsigned char *data,
581                            SilcUInt32 data_len,
582                            SilcHash hash)
583 {
584   return FALSE;
585 }
586
587 /* PKCS #1 sign without hash oid */
588
589 SilcBool silc_pkcs1_sign_no_oid(void *private_key,
590                                 unsigned char *src,
591                                 SilcUInt32 src_len,
592                                 unsigned char *signature,
593                                 SilcUInt32 signature_size,
594                                 SilcUInt32 *ret_signature_len,
595                                 SilcHash hash)
596 {
597   RsaPrivateKey *key = private_key;
598   SilcMPInt mp_tmp;
599   SilcMPInt mp_dst;
600   unsigned char padded[2048 + 1], hashr[SILC_HASH_MAXLEN];
601   SilcUInt32 len = (key->bits + 7) / 8;
602
603   if (sizeof(padded) < len)
604     return FALSE;
605   if (signature_size < len)
606     return FALSE;
607
608   /* Compute hash if requested */
609   if (hash) {
610     silc_hash_make(hash, src, src_len, hashr);
611     src = hashr;
612     src_len = silc_hash_len(hash);
613   }
614
615   /* Pad data */
616   if (!silc_pkcs1_encode(SILC_PKCS1_BT_PRV1, src, src_len,
617                          padded, len, NULL))
618     return FALSE;
619
620   silc_mp_init(&mp_tmp);
621   silc_mp_init(&mp_dst);
622
623   /* Data to MP */
624   silc_mp_bin2mp(padded, len, &mp_tmp);
625
626   /* Sign */
627   rsa_private_operation(key, &mp_tmp, &mp_dst);
628
629   /* MP to data */
630   silc_mp_mp2bin_noalloc(&mp_dst, signature, len);
631   *ret_signature_len = len;
632
633   memset(padded, 0, sizeof(padded));
634   silc_mp_uninit(&mp_tmp);
635   silc_mp_uninit(&mp_dst);
636   if (hash)
637     memset(hashr, 0, sizeof(hashr));
638
639   return TRUE;
640 }
641
642 /* PKCS #1 verify without hash oid */
643
644 SilcBool silc_pkcs1_verify_no_oid(void *public_key,
645                                   unsigned char *signature,
646                                   SilcUInt32 signature_len,
647                                   unsigned char *data,
648                                   SilcUInt32 data_len,
649                                   SilcHash hash)
650 {
651   RsaPublicKey *key = public_key;
652   int ret = TRUE;
653   SilcMPInt mp_tmp2;
654   SilcMPInt mp_dst;
655   unsigned char *verify, unpadded[2048 + 1], hashr[SILC_HASH_MAXLEN];
656   SilcUInt32 verify_len, len = (key->bits + 7) / 8;
657
658   silc_mp_init(&mp_tmp2);
659   silc_mp_init(&mp_dst);
660
661   /* Format the signature into MP int */
662   silc_mp_bin2mp(signature, signature_len, &mp_tmp2);
663
664   /* Verify */
665   rsa_public_operation(key, &mp_tmp2, &mp_dst);
666
667   /* MP to data */
668   verify = silc_mp_mp2bin(&mp_dst, len, &verify_len);
669
670   /* Unpad data */
671   if (!silc_pkcs1_decode(SILC_PKCS1_BT_PRV1, verify, verify_len,
672                          unpadded, sizeof(unpadded), &len)) {
673     memset(verify, 0, verify_len);
674     silc_free(verify);
675     silc_mp_uninit(&mp_tmp2);
676     silc_mp_uninit(&mp_dst);
677     return FALSE;
678   }
679
680   /* Hash data if requested */
681   if (hash) {
682     silc_hash_make(hash, data, data_len, hashr);
683     data = hashr;
684     data_len = silc_hash_len(hash);
685   }
686
687   /* Compare */
688   if (len != data_len)
689     ret = FALSE;
690   else if (memcmp(data, unpadded, len))
691     ret = FALSE;
692
693   memset(verify, 0, verify_len);
694   memset(unpadded, 0, sizeof(unpadded));
695   silc_free(verify);
696   silc_mp_uninit(&mp_tmp2);
697   silc_mp_uninit(&mp_dst);
698   if (hash)
699     memset(hashr, 0, sizeof(hashr));
700
701   return ret;
702 }