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