59f1dad7835d4a04c950cfa9b8d31b2d78373082
[oweals/gnunet.git] / src / include / gnunet_crypto_lib.h
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2012 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file include/gnunet_crypto_lib.h
23  * @brief cryptographic primitives for GNUnet
24  *
25  * @author Christian Grothoff
26  * @author Krista Bennett
27  * @author Gerd Knorr <kraxel@bytesex.org>
28  * @author Ioana Patrascu
29  * @author Tzvetan Horozov
30  */
31
32 #ifndef GNUNET_CRYPTO_LIB_H
33 #define GNUNET_CRYPTO_LIB_H
34
35 #ifdef __cplusplus
36 extern "C"
37 {
38 #if 0                           /* keep Emacsens' auto-indent happy */
39 }
40 #endif
41 #endif
42
43 #include "gnunet_common.h"
44 #include "gnunet_scheduler_lib.h"
45
46 /**
47  * Desired quality level for cryptographic operations.
48  */
49 enum GNUNET_CRYPTO_Quality
50 {
51   /**
52    * No good quality of the operation is needed (i.e.,
53    * random numbers can be pseudo-random).
54    */
55   GNUNET_CRYPTO_QUALITY_WEAK,
56
57   /**
58    * High-quality operations are desired.
59    */
60   GNUNET_CRYPTO_QUALITY_STRONG,
61
62   /**
63    * Randomness for IVs etc. is required.
64    */
65   GNUNET_CRYPTO_QUALITY_NONCE
66 };
67
68
69 /**
70  * @brief length of the sessionkey in bytes (256 BIT sessionkey)
71  */
72 #define GNUNET_CRYPTO_AES_KEY_LENGTH (256/8)
73
74
75 /**
76  * @brief Length of RSA encrypted data (2048 bit)
77  *
78  * We currently do not handle encryption of data
79  * that can not be done in a single call to the
80  * RSA methods (read: large chunks of data).
81  * We should never need that, as we can use
82  * the GNUNET_CRYPTO_hash for larger pieces of data for signing,
83  * and for encryption, we only need to encode sessionkeys!
84  */
85 #define GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH 256
86
87
88 /**
89  * Length of an RSA KEY (n,e,len), 2048 bit (=256 octests) key n, 2 byte e
90  */
91 #define GNUNET_CRYPTO_RSA_KEY_LENGTH 258
92
93
94 /**
95  * Length of a hash value
96  */
97 #define GNUNET_CRYPTO_HASH_LENGTH 512/8
98
99
100 /**
101  * FIXME: what is an acceptable value here?
102  * Note: round to multiple of 8 minus 2.
103  */
104 #define GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH 510
105
106 /**
107  * FIXME: what is an acceptable value here?
108  * Maximum length of the public key (q-point, Q = dP) when encoded.
109  */
110 #define GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH 254
111
112
113 /**
114  * The private information of an RSA key pair.
115  */
116 struct GNUNET_CRYPTO_RsaPrivateKey;
117
118 /**
119  * The private information of an ECC private key.
120  */
121 struct GNUNET_CRYPTO_EccPrivateKey;
122
123
124 GNUNET_NETWORK_STRUCT_BEGIN
125
126 /**
127  * GNUnet mandates a certain format for the encoding
128  * of private RSA key information that is provided
129  * by the RSA implementations.  This format is used
130  * to serialize a private RSA key (typically when
131  * writing it to disk).
132  */
133 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded
134 {
135   /**
136    * Total size of the structure, in bytes, in big-endian!
137    */
138   uint16_t len GNUNET_PACKED;
139   uint16_t sizen GNUNET_PACKED; /*  in big-endian! */
140   uint16_t sizee GNUNET_PACKED; /*  in big-endian! */
141   uint16_t sized GNUNET_PACKED; /*  in big-endian! */
142   uint16_t sizep GNUNET_PACKED; /*  in big-endian! */
143   uint16_t sizeq GNUNET_PACKED; /*  in big-endian! */
144   uint16_t sizedmp1 GNUNET_PACKED;      /*  in big-endian! */
145   uint16_t sizedmq1 GNUNET_PACKED;      /*  in big-endian! */
146   /* followed by the actual values */
147 };
148 GNUNET_NETWORK_STRUCT_END
149
150
151 /**
152  * @brief 0-terminated ASCII encoding of a struct GNUNET_HashCode.
153  */
154 struct GNUNET_CRYPTO_HashAsciiEncoded
155 {
156   unsigned char encoding[104];
157 };
158
159
160 /**
161  * @brief 0-terminated ASCII encoding of a 'struct GNUNET_ShortHashCode'.
162  */
163 struct GNUNET_CRYPTO_ShortHashAsciiEncoded
164 {
165   unsigned char short_encoding[53];
166 };
167
168
169
170 /**
171  * @brief an RSA signature
172  */
173 struct GNUNET_CRYPTO_RsaSignature
174 {
175   unsigned char sig[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
176 };
177
178
179 GNUNET_NETWORK_STRUCT_BEGIN
180
181 /**
182  * @brief header of what an RSA signature signs
183  *        this must be followed by "size - 8" bytes of
184  *        the actual signed data
185  */
186 struct GNUNET_CRYPTO_RsaSignaturePurpose
187 {
188   /**
189    * How many bytes does this signature sign?
190    * (including this purpose header); in network
191    * byte order (!).
192    */
193   uint32_t size GNUNET_PACKED;
194
195   /**
196    * What does this signature vouch for?  This
197    * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
198    * constant (from gnunet_signatures.h).  In
199    * network byte order!
200    */
201   uint32_t purpose GNUNET_PACKED;
202
203 };
204
205
206 /**
207  * @brief A public key.
208  */
209 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
210 {
211   /**
212    * In big-endian, must be GNUNET_CRYPTO_RSA_KEY_LENGTH+4
213    */
214   uint16_t len GNUNET_PACKED;
215
216   /**
217    * Size of n in key; in big-endian!
218    */
219   uint16_t sizen GNUNET_PACKED;
220
221   /**
222    * The key itself, contains n followed by e.
223    */
224   unsigned char key[GNUNET_CRYPTO_RSA_KEY_LENGTH];
225
226   /**
227    * Padding (must be 0)
228    */
229   uint16_t padding GNUNET_PACKED;
230 };
231
232
233 /**
234  * RSA Encrypted data.
235  */
236 struct GNUNET_CRYPTO_RsaEncryptedData
237 {
238   unsigned char encoding[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
239 };
240
241
242 /**
243  * @brief header of what an ECC signature signs
244  *        this must be followed by "size - 8" bytes of
245  *        the actual signed data
246  */
247 struct GNUNET_CRYPTO_EccSignaturePurpose
248 {
249   /**
250    * How many bytes does this signature sign?
251    * (including this purpose header); in network
252    * byte order (!).
253    */
254   uint32_t size GNUNET_PACKED;
255
256   /**
257    * What does this signature vouch for?  This
258    * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
259    * constant (from gnunet_signatures.h).  In
260    * network byte order!
261    */
262   uint32_t purpose GNUNET_PACKED;
263
264 };
265
266
267 /**
268  * @brief an ECC signature
269  */
270 struct GNUNET_CRYPTO_EccSignature
271 {
272   /**
273    * Overall size of the encrypted data.
274    */
275   uint16_t size;
276
277   /**
278    * S-expression, padded with zeros.
279    */
280   char sexpr[GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH];
281 };
282
283
284 /**
285  * Public ECC key (always for NIST P-521) encoded in a format suitable
286  * for network transmission as created using 'gcry_sexp_sprint'.
287  */
288 struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded 
289 {
290   /**
291    * Size of the encoding, in network byte order.
292    */
293   uint16_t size;
294
295   /**
296    * Actual length of the q-point binary encoding.
297    */
298   uint16_t len;
299
300   /**
301    * 0-padded q-point in binary encoding (GCRYPT_MPI_FMT_USG).
302    */
303   unsigned char key[GNUNET_CRYPTO_ECC_MAX_PUBLIC_KEY_LENGTH];
304 };
305
306
307 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded
308 {
309   /**
310    * Overall size of the private key.
311    */
312   uint16_t size;
313
314   /* followd by S-expression, opaque to applications */
315
316   /* FIXME: consider defining padding to make this a fixed-size struct */
317
318 };
319
320
321 /**
322  * ECC Encrypted data.
323  */
324 struct GNUNET_CRYPTO_EccEncryptedData
325 {
326   /**
327    * Overall size of the encrypted data.
328    */
329   uint16_t size;
330
331   /**
332    * S-expression, padded with zeros.
333    */
334   char encoding[GNUNET_CRYPTO_ECC_DATA_ENCODING_LENGTH];
335 };
336
337
338 /**
339  * @brief type for session keys
340  */
341 struct GNUNET_CRYPTO_AesSessionKey
342 {
343   /**
344    * Actual key.
345    */
346   unsigned char key[GNUNET_CRYPTO_AES_KEY_LENGTH];
347
348   /**
349    * checksum!
350    */
351   uint32_t crc32 GNUNET_PACKED;
352 };
353 GNUNET_NETWORK_STRUCT_END
354
355 /**
356  * @brief IV for sym cipher
357  *
358  * NOTE: must be smaller (!) in size than the
359  * struct GNUNET_HashCode.
360  */
361 struct GNUNET_CRYPTO_AesInitializationVector
362 {
363   unsigned char iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
364 };
365
366
367 /**
368  * @brief type for (message) authentication keys
369  */
370 struct GNUNET_CRYPTO_AuthKey
371 {
372   unsigned char key[GNUNET_CRYPTO_HASH_LENGTH];
373 };
374
375
376 /* **************** Functions and Macros ************* */
377
378 /**
379  * Seed a weak random generator. Only GNUNET_CRYPTO_QUALITY_WEAK-mode generator
380  * can be seeded.
381  *
382  * @param seed the seed to use
383  */
384 void
385 GNUNET_CRYPTO_seed_weak_random (int32_t seed);
386
387
388 /**
389  * Perform an incremental step in a CRC16 (for TCP/IP) calculation.
390  *
391  * @param sum current sum, initially 0
392  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
393  * @param len number of bytes in hdr, must be multiple of 2
394  * @return updated crc sum (must be subjected to GNUNET_CRYPTO_crc16_finish to get actual crc16)
395  */
396 uint32_t
397 GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len);
398
399
400 /**
401  * Convert results from GNUNET_CRYPTO_crc16_step to final crc16.
402  *
403  * @param sum cummulative sum
404  * @return crc16 value
405  */
406 uint16_t
407 GNUNET_CRYPTO_crc16_finish (uint32_t sum);
408
409
410 /**
411  * Calculate the checksum of a buffer in one step.
412  *
413  * @param buf buffer to  calculate CRC over (must be 16-bit aligned)
414  * @param len number of bytes in hdr, must be multiple of 2
415  * @return crc16 value
416  */
417 uint16_t
418 GNUNET_CRYPTO_crc16_n (const void *buf, size_t len);
419
420
421 /**
422  * Compute the CRC32 checksum for the first len
423  * bytes of the buffer.
424  *
425  * @param buf the data over which we're taking the CRC
426  * @param len the length of the buffer in bytes
427  * @return the resulting CRC32 checksum
428  */
429 int32_t
430 GNUNET_CRYPTO_crc32_n (const void *buf, size_t len);
431
432
433 /**
434  * Produce a random value.
435  *
436  * @param mode desired quality of the random number
437  * @param i the upper limit (exclusive) for the random number
438  * @return a random value in the interval [0,i) (exclusive).
439  */
440 uint32_t
441 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i);
442
443
444 /**
445  * Random on unsigned 64-bit values.
446  *
447  * @param mode desired quality of the random number
448  * @param max value returned will be in range [0,max) (exclusive)
449  * @return random 64-bit number
450  */
451 uint64_t
452 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max);
453
454
455 /**
456  * Get an array with a random permutation of the
457  * numbers 0...n-1.
458  * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
459  * @param n the size of the array
460  * @return the permutation array (allocated from heap)
461  */
462 unsigned int *
463 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n);
464
465
466 /**
467  * Create a new Session key.
468  *
469  * @param key key to initialize
470  */
471 void
472 GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey *key);
473
474
475 /**
476  * Check that a new session key is well-formed.
477  *
478  * @param key key to check
479  * @return GNUNET_OK if the key is valid
480  */
481 int
482 GNUNET_CRYPTO_aes_check_session_key (const struct GNUNET_CRYPTO_AesSessionKey
483                                      *key);
484
485
486 /**
487  * Encrypt a block with the public key of another
488  * host that uses the same cyper.
489  *
490  * @param block the block to encrypt
491  * @param len the size of the block
492  * @param sessionkey the key used to encrypt
493  * @param iv the initialization vector to use, use INITVALUE
494  *        for streams.
495  * @return the size of the encrypted block, -1 for errors
496  */
497 ssize_t
498 GNUNET_CRYPTO_aes_encrypt (const void *block, size_t len,
499                            const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
500                            const struct GNUNET_CRYPTO_AesInitializationVector
501                            *iv, void *result);
502
503
504 /**
505  * Decrypt a given block with the sessionkey.
506  *
507  * @param block the data to decrypt, encoded as returned by encrypt
508  * @param size how big is the block?
509  * @param sessionkey the key used to decrypt
510  * @param iv the initialization vector to use
511  * @param result address to store the result at
512  * @return -1 on failure, size of decrypted block on success
513  */
514 ssize_t
515 GNUNET_CRYPTO_aes_decrypt (const void *block, size_t size,
516                            const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
517                            const struct GNUNET_CRYPTO_AesInitializationVector
518                            *iv, void *result);
519
520
521 /**
522  * @brief Derive an IV
523  * @param iv initialization vector
524  * @param skey session key
525  * @param salt salt for the derivation
526  * @param salt_len size of the salt
527  * @param ... pairs of void * & size_t for context chunks, terminated by NULL
528  */
529 void
530 GNUNET_CRYPTO_aes_derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
531                              const struct GNUNET_CRYPTO_AesSessionKey *skey,
532                              const void *salt, size_t salt_len, ...);
533
534
535 /**
536  * @brief Derive an IV
537  * @param iv initialization vector
538  * @param skey session key
539  * @param salt salt for the derivation
540  * @param salt_len size of the salt
541  * @param argp pairs of void * & size_t for context chunks, terminated by NULL
542  */
543 void
544 GNUNET_CRYPTO_aes_derive_iv_v (struct GNUNET_CRYPTO_AesInitializationVector *iv,
545                                const struct GNUNET_CRYPTO_AesSessionKey *skey,
546                                const void *salt, size_t salt_len, va_list argp);
547
548
549 /**
550  * Convert hash to ASCII encoding.
551  * @param block the hash code
552  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
553  *  safely cast to char*, a '\\0' termination is set).
554  */
555 void
556 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode * block,
557                            struct GNUNET_CRYPTO_HashAsciiEncoded *result);
558
559
560 /**
561  * Convert short hash to ASCII encoding.
562  *
563  * @param block the hash code
564  * @param result where to store the encoding (struct GNUNET_CRYPTO_ShortHashAsciiEncoded can be
565  *  safely cast to char*, a '\\0' termination is set).
566  */
567 void
568 GNUNET_CRYPTO_short_hash_to_enc (const struct GNUNET_CRYPTO_ShortHashCode * block,
569                                  struct GNUNET_CRYPTO_ShortHashAsciiEncoded *result);
570
571
572 /**
573  * Convert ASCII encoding back to a 'struct GNUNET_HashCode'
574  *
575  * @param enc the encoding
576  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
577  * @param result where to store the GNUNET_CRYPTO_hash code
578  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
579  */
580 int
581 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
582                                  struct GNUNET_HashCode * result);
583
584
585 /**
586  * Convert ASCII encoding back to a 'struct GNUNET_CRYPTO_ShortHash'
587  *
588  * @param enc the encoding
589  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
590  * @param result where to store the GNUNET_CRYPTO_hash code
591  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
592  */
593 int
594 GNUNET_CRYPTO_short_hash_from_string2 (const char *enc, size_t enclen,
595                                        struct GNUNET_CRYPTO_ShortHashCode * result);
596
597
598 /**
599  * Convert ASCII encoding back to struct GNUNET_HashCode
600  *
601  * @param enc the encoding
602  * @param result where to store the hash code
603  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
604  */
605 #define GNUNET_CRYPTO_hash_from_string(enc, result) \
606   GNUNET_CRYPTO_hash_from_string2 (enc, strlen(enc), result)
607
608
609 /**
610  * Convert ASCII encoding back to a 'struct GNUNET_CRYPTO_ShortHash'
611  *
612  * @param enc the encoding
613  * @param result where to store the GNUNET_CRYPTO_ShortHash 
614  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
615  */
616 #define GNUNET_CRYPTO_short_hash_from_string(enc, result) \
617   GNUNET_CRYPTO_short_hash_from_string2 (enc, strlen(enc), result)
618
619
620 /**
621  * Compare function for ShortHashCodes, producing a total ordering
622  * of all hashcodes.
623  *
624  * @param h1 some hash code
625  * @param h2 some hash code
626  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
627  */
628 int
629 GNUNET_CRYPTO_short_hash_cmp (const struct GNUNET_CRYPTO_ShortHashCode * h1,
630                               const struct GNUNET_CRYPTO_ShortHashCode * h2);
631
632 /**
633  * Compute the distance between 2 hashcodes.
634  * The computation must be fast, not involve
635  * a.a or a.e (they're used elsewhere), and
636  * be somewhat consistent. And of course, the
637  * result should be a positive number.
638  *
639  * @param a some hash code
640  * @param b some hash code
641  * @return number between 0 and UINT32_MAX
642  */
643 uint32_t
644 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode * a,
645                                  const struct GNUNET_HashCode * b);
646
647
648 /**
649  * Compute hash of a given block.
650  *
651  * @param block the data to hash
652  * @param size size of the block
653  * @param ret pointer to where to write the hashcode
654  */
655 void
656 GNUNET_CRYPTO_hash (const void *block, size_t size, struct GNUNET_HashCode * ret);
657
658
659 /**
660  * Compute short (256-bit) hash of a given block.
661  *
662  * @param block the data to hash
663  * @param size size of the block
664  * @param ret pointer to where to write the hashcode
665  */
666 void
667 GNUNET_CRYPTO_short_hash (const void *block, size_t size, 
668                           struct GNUNET_CRYPTO_ShortHashCode * ret);
669
670
671 /**
672  * Double short (256-bit) hash to create a long hash.
673  *
674  * @param sh short hash to double
675  * @param dh where to store the (doubled) long hash (not really a hash)
676  */
677 void
678 GNUNET_CRYPTO_short_hash_double (const struct GNUNET_CRYPTO_ShortHashCode *sh,
679                                  struct GNUNET_HashCode *dh);
680
681
682 /**
683  * Truncate doubled short hash back to a short hash.
684  *
685  * @param dh doubled short hash to reduce again
686  * @param sh where to store the short hash
687  * @return GNUNET_OK on success, GNUNET_SYSERR if this was not a
688  *         doubled short hash
689  */
690 int
691 GNUNET_CRYPTO_short_hash_from_truncation (const struct GNUNET_HashCode *dh,
692                                           struct GNUNET_CRYPTO_ShortHashCode *sh);
693
694
695 /**
696  * Calculate HMAC of a message (RFC 2104)
697  *
698  * @param key secret key
699  * @param plaintext input plaintext
700  * @param plaintext_len length of plaintext
701  * @param hmac where to store the hmac
702  */
703 void
704 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
705                     const void *plaintext, size_t plaintext_len,
706                     struct GNUNET_HashCode * hmac);
707
708
709 /**
710  * Function called once the hash computation over the
711  * specified file has completed.
712  *
713  * @param cls closure
714  * @param res resulting hash, NULL on error
715  */
716 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
717                                                      const struct GNUNET_HashCode *
718                                                      res);
719
720
721 /**
722  * Handle to file hashing operation.
723  */
724 struct GNUNET_CRYPTO_FileHashContext;
725
726 /**
727  * Compute the hash of an entire file.
728  *
729  * @param priority scheduling priority to use
730  * @param filename name of file to hash
731  * @param blocksize number of bytes to process in one task
732  * @param callback function to call upon completion
733  * @param callback_cls closure for callback
734  * @return NULL on (immediate) errror
735  */
736 struct GNUNET_CRYPTO_FileHashContext *
737 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
738                          const char *filename, size_t blocksize,
739                          GNUNET_CRYPTO_HashCompletedCallback callback,
740                          void *callback_cls);
741
742
743 /**
744  * Cancel a file hashing operation.
745  *
746  * @param fhc operation to cancel (callback must not yet have been invoked)
747  */
748 void
749 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
750
751
752 /**
753  * Create a random hash code.
754  *
755  * @param mode desired quality level
756  * @param result hash code that is randomized
757  */
758 void
759 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
760                                   struct GNUNET_HashCode * result);
761
762
763 /**
764  * compute result(delta) = b - a
765  *
766  * @param a some hash code
767  * @param b some hash code
768  * @param result set to b - a
769  */
770 void
771 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode * a,
772                                const struct GNUNET_HashCode * b,
773                                struct GNUNET_HashCode * result);
774
775
776 /**
777  * compute result(b) = a + delta
778  *
779  * @param a some hash code
780  * @param delta some hash code
781  * @param result set to a + delta
782  */
783 void
784 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
785                         const struct GNUNET_HashCode * delta,
786                         struct GNUNET_HashCode * result);
787
788
789 /**
790  * compute result = a ^ b
791  *
792  * @param a some hash code
793  * @param b some hash code
794  * @param result set to a ^ b
795  */
796 void
797 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode * a, const struct GNUNET_HashCode * b,
798                         struct GNUNET_HashCode * result);
799
800
801 /**
802  * Convert a hashcode into a key.
803  *
804  * @param hc hash code that serves to generate the key
805  * @param skey set to a valid session key
806  * @param iv set to a valid initialization vector
807  */
808 void
809 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
810                                struct GNUNET_CRYPTO_AesSessionKey *skey,
811                                struct GNUNET_CRYPTO_AesInitializationVector
812                                *iv);
813
814
815 /**
816  * Obtain a bit from a hashcode.
817  *
818  * @param code the GNUNET_CRYPTO_hash to index bit-wise
819  * @param bit index into the hashcode, [0...159]
820  * @return Bit \a bit from hashcode \a code, -1 for invalid index
821  */
822 int
823 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit);
824
825 /**
826  * Determine how many low order bits match in two
827  * struct GNUNET_HashCodes.  i.e. - 010011 and 011111 share
828  * the first two lowest order bits, and therefore the
829  * return value is two (NOT XOR distance, nor how many
830  * bits match absolutely!).
831  *
832  * @param first the first hashcode
833  * @param second the hashcode to compare first to
834  *
835  * @return the number of bits that match
836  */
837 unsigned int
838 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
839                                   const struct GNUNET_HashCode * second);
840
841
842 /**
843  * Compare function for HashCodes, producing a total ordering
844  * of all hashcodes.
845  *
846  * @param h1 some hash code
847  * @param h2 some hash code
848  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
849  */
850 int
851 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode * h1, const struct GNUNET_HashCode * h2);
852
853
854 /**
855  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
856  * in the XOR metric (Kademlia).
857  *
858  * @param h1 some hash code
859  * @param h2 some hash code
860  * @param target some hash code
861  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
862  */
863 int
864 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode * h1,
865                            const struct GNUNET_HashCode * h2,
866                            const struct GNUNET_HashCode * target);
867
868
869 /**
870  * @brief Derive an authentication key
871  * @param key authentication key
872  * @param rkey root key
873  * @param salt salt
874  * @param salt_len size of the salt
875  * @param argp pair of void * & size_t for context chunks, terminated by NULL
876  */
877 void
878 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
879                                  const struct GNUNET_CRYPTO_AesSessionKey *rkey,
880                                  const void *salt, size_t salt_len,
881                                  va_list argp);
882
883
884 /**
885  * @brief Derive an authentication key
886  * @param key authentication key
887  * @param rkey root key
888  * @param salt salt
889  * @param salt_len size of the salt
890  * @param ... pair of void * & size_t for context chunks, terminated by NULL
891  */
892 void
893 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
894                                const struct GNUNET_CRYPTO_AesSessionKey *rkey,
895                                const void *salt, size_t salt_len, ...);
896
897 /**
898  * @brief Derive key
899  * @param result buffer for the derived key, allocated by caller
900  * @param out_len desired length of the derived key
901  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
902  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
903  * @param xts salt
904  * @param xts_len length of xts
905  * @param skm source key material
906  * @param skm_len length of skm
907  * @return GNUNET_YES on success
908  */
909 int
910 GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo, int prf_algo,
911                     const void *xts, size_t xts_len, const void *skm,
912                     size_t skm_len, ...);
913
914
915 /**
916  * @brief Derive key
917  * @param result buffer for the derived key, allocated by caller
918  * @param out_len desired length of the derived key
919  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
920  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
921  * @param xts salt
922  * @param xts_len length of xts
923  * @param skm source key material
924  * @param skm_len length of skm
925  * @param argp va_list of void * & size_t pairs for context chunks
926  * @return GNUNET_YES on success
927  */
928 int
929 GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
930                       const void *xts, size_t xts_len, const void *skm,
931                       size_t skm_len, va_list argp);
932
933
934 /**
935  * @brief Derive key
936  * @param result buffer for the derived key, allocated by caller
937  * @param out_len desired length of the derived key
938  * @param xts salt
939  * @param xts_len length of xts
940  * @param skm source key material
941  * @param skm_len length of skm
942  * @param argp va_list of void * & size_t pairs for context chunks
943  * @return GNUNET_YES on success
944  */
945 int
946 GNUNET_CRYPTO_kdf_v (void *result, size_t out_len, const void *xts,
947                      size_t xts_len, const void *skm, size_t skm_len,
948                      va_list argp);
949
950
951 /**
952  * @brief Derive key
953  * @param result buffer for the derived key, allocated by caller
954  * @param out_len desired length of the derived key
955  * @param xts salt
956  * @param xts_len length of xts
957  * @param skm source key material
958  * @param skm_len length of skm
959  * @param ... void * & size_t pairs for context chunks
960  * @return GNUNET_YES on success
961  */
962 int
963 GNUNET_CRYPTO_kdf (void *result, size_t out_len, const void *xts,
964                    size_t xts_len, const void *skm, size_t skm_len, ...);
965
966
967 /**
968  * Convert a public key to a string.
969  *
970  * @param pub key to convert
971  * @return string representing  'pub'
972  */
973 char *
974 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub);
975
976
977 /**
978  * Convert a string representing a public key to a public key.
979  *
980  * @param enc encoded public key
981  * @param enclen number of bytes in enc (without 0-terminator)
982  * @param pub where to store the public key
983  * @return GNUNET_OK on success
984  */
985 int
986 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc, 
987                                           size_t enclen,
988                                           struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub);
989
990
991 /**
992  * Encode the private key in a format suitable for
993  * storing it into a file.
994  * @return encoding of the private key
995  */
996 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
997 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
998
999
1000 /**
1001  * Decode the private key from the data-format back
1002  * to the "normal", internal format.
1003  *
1004  * @param buf the buffer where the private key data is stored
1005  * @param len the length of the data in 'buffer'
1006  * @return NULL on error
1007  */
1008 struct GNUNET_CRYPTO_RsaPrivateKey *
1009 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len);
1010
1011
1012 /**
1013  * Create a new private key by reading it from a file.  If the
1014  * files does not exist, create a new key and write it to the
1015  * file.  Caller must free return value. Note that this function
1016  * can not guarantee that another process might not be trying
1017  * the same operation on the same file at the same time.
1018  * If the contents of the file
1019  * are invalid the old file is deleted and a fresh key is
1020  * created.
1021  *
1022  * @param filename name of file to use for storage
1023  * @return new private key, NULL on error (for example,
1024  *   permission denied)
1025  * @deprecated use 'GNUNET_CRYPTO_rsa_key_create_start' instead
1026  */
1027 struct GNUNET_CRYPTO_RsaPrivateKey *
1028 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
1029
1030
1031 /**
1032  * Handle to cancel private key generation.
1033  */
1034 struct GNUNET_CRYPTO_RsaKeyGenerationContext;
1035
1036
1037 /**
1038  * Function called upon completion of 'GNUNET_CRYPTO_rsa_key_create_async'.
1039  *
1040  * @param cls closure
1041  * @param pk NULL on error, otherwise the private key (which must be free'd by the callee)
1042  * @param emsg NULL on success, otherwise an error message
1043  */
1044 typedef void (*GNUNET_CRYPTO_RsaKeyCallback)(void *cls,
1045                                              struct GNUNET_CRYPTO_RsaPrivateKey *pk,
1046                                              const char *emsg);
1047
1048
1049 /**
1050  * Create a new private key by reading it from a file.  If the files
1051  * does not exist, create a new key and write it to the file.  If the
1052  * contents of the file are invalid the old file is deleted and a
1053  * fresh key is created.
1054  *
1055  * @param filename name of file to use for storage
1056  * @param cont function to call when done (or on errors)
1057  * @param cont_cls closure for 'cont'
1058  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1059  */
1060 struct GNUNET_CRYPTO_RsaKeyGenerationContext *
1061 GNUNET_CRYPTO_rsa_key_create_start (const char *filename,
1062                                     GNUNET_CRYPTO_RsaKeyCallback cont,
1063                                     void *cont_cls);
1064
1065
1066 /**
1067  * Abort RSA key generation.
1068  *
1069  * @param gc key generation context to abort
1070  */
1071 void
1072 GNUNET_CRYPTO_rsa_key_create_stop (struct GNUNET_CRYPTO_RsaKeyGenerationContext *gc);
1073
1074
1075 /**
1076  * Setup a hostkey file for a peer given the name of the
1077  * configuration file (!).  This function is used so that
1078  * at a later point code can be certain that reading a
1079  * hostkey is fast (for example in time-dependent testcases).
1080  *
1081  * @param cfg_name name of the configuration file to use
1082  */
1083 void
1084 GNUNET_CRYPTO_rsa_setup_hostkey (const char *cfg_name);
1085
1086
1087 /**
1088  * Deterministically (!) create a private key using only the
1089  * given HashCode as input to the PRNG.
1090  *
1091  * @param hc "random" input to PRNG
1092  * @return some private key purely dependent on input
1093  */
1094 struct GNUNET_CRYPTO_RsaPrivateKey *
1095 GNUNET_CRYPTO_rsa_key_create_from_hash (const struct GNUNET_HashCode *hc);
1096
1097
1098 /**
1099  * Free memory occupied by the private key.
1100  *
1101  * @param key pointer to the memory to free
1102  */
1103 void
1104 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key);
1105
1106
1107 /**
1108  * Extract the public key of the host.
1109  *
1110  * @param priv the private key
1111  * @param pub where to write the public key
1112  */
1113 void
1114 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
1115                                   *priv,
1116                                   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1117                                   *pub);
1118
1119
1120 /**
1121  * Encrypt a block with the public key of another host that uses the
1122  * same cyper.
1123  *
1124  * @param block the block to encrypt
1125  * @param size the size of block
1126  * @param publicKey the encoded public key used to encrypt
1127  * @param target where to store the encrypted block
1128  * @return GNUNET_SYSERR on error, GNUNET_OK if ok
1129  */
1130 int
1131 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1132                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1133                            *publicKey,
1134                            struct GNUNET_CRYPTO_RsaEncryptedData *target);
1135
1136
1137 /**
1138  * Decrypt a given block with the hostkey.
1139  *
1140  * @param key the key to use
1141  * @param block the data to decrypt, encoded as returned by encrypt, not consumed
1142  * @param result pointer to a location where the result can be stored
1143  * @param max how many bytes of a result are expected? Must be exact.
1144  * @return the size of the decrypted block (that is, size) or -1 on error
1145  */
1146 ssize_t
1147 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1148                            const struct GNUNET_CRYPTO_RsaEncryptedData *block,
1149                            void *result, size_t max);
1150
1151
1152 /**
1153  * Sign a given block.
1154  *
1155  * @param key private key to use for the signing
1156  * @param purpose what to sign (size, purpose)
1157  * @param sig where to write the signature
1158  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1159  */
1160 int
1161 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1162                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1163                         struct GNUNET_CRYPTO_RsaSignature *sig);
1164
1165
1166 /**
1167  * Verify signature.  Note that the caller MUST have already
1168  * checked that "validate->size" bytes are actually available.
1169  *
1170  * @param purpose what is the purpose that validate should have?
1171  * @param validate block to validate (size, purpose, data)
1172  * @param sig signature that is being validated
1173  * @param publicKey public key of the signer
1174  * @return GNUNET_OK if ok, GNUNET_SYSERR if invalid
1175  */
1176 int
1177 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1178                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
1179                           *validate,
1180                           const struct GNUNET_CRYPTO_RsaSignature *sig,
1181                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1182                           *publicKey);
1183
1184
1185
1186 /**
1187  * Function called upon completion of 'GNUNET_CRYPTO_ecc_key_create_async'.
1188  *
1189  * @param cls closure
1190  * @param pk NULL on error, otherwise the private key (which must be free'd by the callee)
1191  * @param emsg NULL on success, otherwise an error message
1192  */
1193 typedef void (*GNUNET_CRYPTO_EccKeyCallback)(void *cls,
1194                                              struct GNUNET_CRYPTO_EccPrivateKey *pk,
1195                                              const char *emsg);
1196
1197
1198 /**
1199  * Free memory occupied by ECC key
1200  *
1201  * @param privatekey pointer to the memory to free
1202  */
1203 void
1204 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey);
1205
1206
1207 /**
1208  * Extract the public key for the given private key.
1209  *
1210  * @param priv the private key
1211  * @param pub where to write the public key
1212  */
1213 void
1214 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
1215                                   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub);
1216
1217 /**
1218  * Convert a public key to a string.
1219  *
1220  * @param pub key to convert
1221  * @return string representing  'pub'
1222  */
1223 char *
1224 GNUNET_CRYPTO_ecc_public_key_to_string (struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub);
1225
1226
1227 /**
1228  * Convert a string representing a public key to a public key.
1229  *
1230  * @param enc encoded public key
1231  * @param enclen number of bytes in enc (without 0-terminator)
1232  * @param pub where to store the public key
1233  * @return GNUNET_OK on success
1234  */
1235 int
1236 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc, 
1237                                           size_t enclen,
1238                                           struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub);
1239
1240
1241 /**
1242  * Encode the private key in a format suitable for
1243  * storing it into a file.
1244  *
1245  * @param key key to encode
1246  * @return encoding of the private key.
1247  *    The first 4 bytes give the size of the array, as usual.
1248  */
1249 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
1250 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key);
1251
1252
1253 /**
1254  * Decode the private key from the file-format back
1255  * to the "normal", internal format.
1256  *
1257  * @param buf the buffer where the private key data is stored
1258  * @param len the length of the data in 'buffer'
1259  * @return NULL on error
1260  */
1261 struct GNUNET_CRYPTO_EccPrivateKey *
1262 GNUNET_CRYPTO_ecc_decode_key (const char *buf, 
1263                               size_t len);
1264
1265
1266 /**
1267  * Create a new private key by reading it from a file.  If the
1268  * files does not exist, create a new key and write it to the
1269  * file.  Caller must free return value.  Note that this function
1270  * can not guarantee that another process might not be trying
1271  * the same operation on the same file at the same time.
1272  * If the contents of the file
1273  * are invalid the old file is deleted and a fresh key is
1274  * created.
1275  *
1276  * @return new private key, NULL on error (for example,
1277  *   permission denied)
1278  */
1279 struct GNUNET_CRYPTO_EccPrivateKey *
1280 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename);
1281
1282
1283 /**
1284  * Handle to cancel private key generation and state for the
1285  * key generation operation.
1286  */
1287 struct GNUNET_CRYPTO_EccKeyGenerationContext;
1288
1289
1290 /**
1291  * Create a new private key by reading it from a file.  If the files
1292  * does not exist, create a new key and write it to the file.  If the
1293  * contents of the file are invalid the old file is deleted and a
1294  * fresh key is created.
1295  *
1296  * @param filename name of file to use for storage
1297  * @param cont function to call when done (or on errors)
1298  * @param cont_cls closure for 'cont'
1299  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1300  */
1301 struct GNUNET_CRYPTO_EccKeyGenerationContext *
1302 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
1303                                     GNUNET_CRYPTO_EccKeyCallback cont,
1304                                     void *cont_cls);
1305
1306
1307 /**
1308  * Abort ECC key generation.
1309  *
1310  * @param gc key generation context to abort
1311  */
1312 void
1313 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc);
1314
1315 /**
1316  * Setup a hostkey file for a peer given the name of the
1317  * configuration file (!).  This function is used so that
1318  * at a later point code can be certain that reading a
1319  * hostkey is fast (for example in time-dependent testcases).
1320  *
1321  * @param cfg_name name of the configuration file to use
1322  */
1323 void
1324 GNUNET_CRYPTO_ecc_setup_hostkey (const char *cfg_name);
1325
1326
1327 /**
1328  * Encrypt a block with the public key of another host that uses the
1329  * same cipher.
1330  *
1331  * @param block the block to encrypt
1332  * @param size the size of block
1333  * @param publicKey the encoded public key used to encrypt
1334  * @param target where to store the encrypted block
1335  * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
1336  */
1337 int
1338 GNUNET_CRYPTO_ecc_encrypt (const void *block, size_t size,
1339                            const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1340                            *publicKey,
1341                            struct GNUNET_CRYPTO_EccEncryptedData *target);
1342
1343
1344 /**
1345  * Decrypt a given block with the hostkey.
1346  *
1347  * @param key the key with which to decrypt this block
1348  * @param block the data to decrypt, encoded as returned by encrypt
1349  * @param result pointer to a location where the result can be stored
1350  * @param max the maximum number of bits to store for the result, if
1351  *        the decrypted block is bigger, an error is returned
1352  * @return the size of the decrypted block, -1 on error
1353  */
1354 ssize_t
1355 GNUNET_CRYPTO_ecc_decrypt (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1356                            const struct GNUNET_CRYPTO_EccEncryptedData *block,
1357                            void *result, size_t max);
1358
1359
1360 /**
1361  * Sign a given block.
1362  *
1363  * @param key private key to use for the signing
1364  * @param purpose what to sign (size, purpose)
1365  * @param sig where to write the signature
1366  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1367  */
1368 int
1369 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1370                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1371                         struct GNUNET_CRYPTO_EccSignature *sig);
1372
1373
1374 /**
1375  * Verify signature.
1376  *
1377  * @param purpose what is the purpose that the signature should have?
1378  * @param validate block to validate (size, purpose, data)
1379  * @param sig signature that is being validated
1380  * @param publicKey public key of the signer
1381  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1382  */
1383 int
1384 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1385                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1386                           *validate,
1387                           const struct GNUNET_CRYPTO_EccSignature *sig,
1388                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1389                           *publicKey);
1390
1391
1392 /**
1393  * This function should only be called in testcases
1394  * where strong entropy gathering is not desired
1395  * (for example, for hostkey generation).
1396  */
1397 void
1398 GNUNET_CRYPTO_random_disable_entropy_gathering (void);
1399
1400
1401 /**
1402  * Check if we are using weak random number generation.
1403  *
1404  * @return GNUNET_YES if weak number generation is on
1405  *         (thus will return YES if 'GNUNET_CRYPTO_random_disable_entropy_gathering'
1406  *          was called previously).
1407  */
1408 int
1409 GNUNET_CRYPTO_random_is_weak (void);
1410
1411
1412 #if 0                           /* keep Emacsens' auto-indent happy */
1413 {
1414 #endif
1415 #ifdef __cplusplus
1416 }
1417 #endif
1418
1419
1420 /* ifndef GNUNET_CRYPTO_LIB_H */
1421 #endif
1422 /* end of gnunet_crypto_lib.h */