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