- make sure all flow control values are updated correctly
[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 126
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 76 
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 GNUNET_NETWORK_STRUCT_END
328
329 /**
330  * @brief IV for sym cipher
331  *
332  * NOTE: must be smaller (!) in size than the
333  * struct GNUNET_HashCode.
334  */
335 struct GNUNET_CRYPTO_AesInitializationVector
336 {
337   unsigned char iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
338 };
339
340
341 /**
342  * @brief type for (message) authentication keys
343  */
344 struct GNUNET_CRYPTO_AuthKey
345 {
346   unsigned char key[GNUNET_CRYPTO_HASH_LENGTH];
347 };
348
349
350 /* **************** Functions and Macros ************* */
351
352 /**
353  * Seed a weak random generator. Only GNUNET_CRYPTO_QUALITY_WEAK-mode generator
354  * can be seeded.
355  *
356  * @param seed the seed to use
357  */
358 void
359 GNUNET_CRYPTO_seed_weak_random (int32_t seed);
360
361
362 /**
363  * Perform an incremental step in a CRC16 (for TCP/IP) calculation.
364  *
365  * @param sum current sum, initially 0
366  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
367  * @param len number of bytes in hdr, must be multiple of 2
368  * @return updated crc sum (must be subjected to GNUNET_CRYPTO_crc16_finish to get actual crc16)
369  */
370 uint32_t
371 GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len);
372
373
374 /**
375  * Convert results from GNUNET_CRYPTO_crc16_step to final crc16.
376  *
377  * @param sum cummulative sum
378  * @return crc16 value
379  */
380 uint16_t
381 GNUNET_CRYPTO_crc16_finish (uint32_t sum);
382
383
384 /**
385  * Calculate the checksum of a buffer in one step.
386  *
387  * @param buf buffer to  calculate CRC over (must be 16-bit aligned)
388  * @param len number of bytes in hdr, must be multiple of 2
389  * @return crc16 value
390  */
391 uint16_t
392 GNUNET_CRYPTO_crc16_n (const void *buf, size_t len);
393
394
395 /**
396  * Compute the CRC32 checksum for the first len
397  * bytes of the buffer.
398  *
399  * @param buf the data over which we're taking the CRC
400  * @param len the length of the buffer in bytes
401  * @return the resulting CRC32 checksum
402  */
403 int32_t
404 GNUNET_CRYPTO_crc32_n (const void *buf, size_t len);
405
406
407 /**
408  * Produce a random value.
409  *
410  * @param mode desired quality of the random number
411  * @param i the upper limit (exclusive) for the random number
412  * @return a random value in the interval [0,i) (exclusive).
413  */
414 uint32_t
415 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i);
416
417
418 /**
419  * Random on unsigned 64-bit values.
420  *
421  * @param mode desired quality of the random number
422  * @param max value returned will be in range [0,max) (exclusive)
423  * @return random 64-bit number
424  */
425 uint64_t
426 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max);
427
428
429 /**
430  * Get an array with a random permutation of the
431  * numbers 0...n-1.
432  * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
433  * @param n the size of the array
434  * @return the permutation array (allocated from heap)
435  */
436 unsigned int *
437 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n);
438
439
440 /**
441  * Create a new Session key.
442  *
443  * @param key key to initialize
444  */
445 void
446 GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey *key);
447
448
449 /**
450  * Encrypt a block with the public key of another
451  * host that uses the same cyper.
452  *
453  * @param block the block to encrypt
454  * @param len the size of the block
455  * @param sessionkey the key used to encrypt
456  * @param iv the initialization vector to use, use INITVALUE
457  *        for streams.
458  * @return the size of the encrypted block, -1 for errors
459  */
460 ssize_t
461 GNUNET_CRYPTO_aes_encrypt (const void *block, size_t len,
462                            const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
463                            const struct GNUNET_CRYPTO_AesInitializationVector
464                            *iv, void *result);
465
466
467 /**
468  * Decrypt a given block with the sessionkey.
469  *
470  * @param block the data to decrypt, encoded as returned by encrypt
471  * @param size how big is the block?
472  * @param sessionkey the key used to decrypt
473  * @param iv the initialization vector to use
474  * @param result address to store the result at
475  * @return -1 on failure, size of decrypted block on success
476  */
477 ssize_t
478 GNUNET_CRYPTO_aes_decrypt (const void *block, size_t size,
479                            const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
480                            const struct GNUNET_CRYPTO_AesInitializationVector
481                            *iv, void *result);
482
483
484 /**
485  * @brief Derive an IV
486  * @param iv initialization vector
487  * @param skey session key
488  * @param salt salt for the derivation
489  * @param salt_len size of the salt
490  * @param ... pairs of void * & size_t for context chunks, terminated by NULL
491  */
492 void
493 GNUNET_CRYPTO_aes_derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
494                              const struct GNUNET_CRYPTO_AesSessionKey *skey,
495                              const void *salt, size_t salt_len, ...);
496
497
498 /**
499  * @brief Derive an IV
500  * @param iv initialization vector
501  * @param skey session key
502  * @param salt salt for the derivation
503  * @param salt_len size of the salt
504  * @param argp pairs of void * & size_t for context chunks, terminated by NULL
505  */
506 void
507 GNUNET_CRYPTO_aes_derive_iv_v (struct GNUNET_CRYPTO_AesInitializationVector *iv,
508                                const struct GNUNET_CRYPTO_AesSessionKey *skey,
509                                const void *salt, size_t salt_len, va_list argp);
510
511
512 /**
513  * Convert hash to ASCII encoding.
514  * @param block the hash code
515  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
516  *  safely cast to char*, a '\\0' termination is set).
517  */
518 void
519 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode * block,
520                            struct GNUNET_CRYPTO_HashAsciiEncoded *result);
521
522
523 /**
524  * Convert short hash to ASCII encoding.
525  *
526  * @param block the hash code
527  * @param result where to store the encoding (struct GNUNET_CRYPTO_ShortHashAsciiEncoded can be
528  *  safely cast to char*, a '\\0' termination is set).
529  */
530 void
531 GNUNET_CRYPTO_short_hash_to_enc (const struct GNUNET_CRYPTO_ShortHashCode * block,
532                                  struct GNUNET_CRYPTO_ShortHashAsciiEncoded *result);
533
534
535 /**
536  * Convert ASCII encoding back to a 'struct GNUNET_HashCode'
537  *
538  * @param enc the encoding
539  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
540  * @param result where to store the GNUNET_CRYPTO_hash code
541  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
542  */
543 int
544 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
545                                  struct GNUNET_HashCode * result);
546
547
548 /**
549  * Convert ASCII encoding back to a 'struct GNUNET_CRYPTO_ShortHash'
550  *
551  * @param enc the encoding
552  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
553  * @param result where to store the GNUNET_CRYPTO_hash code
554  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
555  */
556 int
557 GNUNET_CRYPTO_short_hash_from_string2 (const char *enc, size_t enclen,
558                                        struct GNUNET_CRYPTO_ShortHashCode * result);
559
560
561 /**
562  * Convert ASCII encoding back to struct GNUNET_HashCode
563  *
564  * @param enc the encoding
565  * @param result where to store the hash code
566  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
567  */
568 #define GNUNET_CRYPTO_hash_from_string(enc, result) \
569   GNUNET_CRYPTO_hash_from_string2 (enc, strlen(enc), result)
570
571
572 /**
573  * Convert ASCII encoding back to a 'struct GNUNET_CRYPTO_ShortHash'
574  *
575  * @param enc the encoding
576  * @param result where to store the GNUNET_CRYPTO_ShortHash 
577  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
578  */
579 #define GNUNET_CRYPTO_short_hash_from_string(enc, result) \
580   GNUNET_CRYPTO_short_hash_from_string2 (enc, strlen(enc), result)
581
582
583 /**
584  * Compare function for ShortHashCodes, producing a total ordering
585  * of all hashcodes.
586  *
587  * @param h1 some hash code
588  * @param h2 some hash code
589  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
590  */
591 int
592 GNUNET_CRYPTO_short_hash_cmp (const struct GNUNET_CRYPTO_ShortHashCode * h1,
593                               const struct GNUNET_CRYPTO_ShortHashCode * h2);
594
595 /**
596  * Compute the distance between 2 hashcodes.
597  * The computation must be fast, not involve
598  * a.a or a.e (they're used elsewhere), and
599  * be somewhat consistent. And of course, the
600  * result should be a positive number.
601  *
602  * @param a some hash code
603  * @param b some hash code
604  * @return number between 0 and UINT32_MAX
605  */
606 uint32_t
607 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode * a,
608                                  const struct GNUNET_HashCode * b);
609
610
611 /**
612  * Compute hash of a given block.
613  *
614  * @param block the data to hash
615  * @param size size of the block
616  * @param ret pointer to where to write the hashcode
617  */
618 void
619 GNUNET_CRYPTO_hash (const void *block, size_t size, struct GNUNET_HashCode * ret);
620
621
622 /**
623  * Compute short (256-bit) hash of a given block.
624  *
625  * @param block the data to hash
626  * @param size size of the block
627  * @param ret pointer to where to write the hashcode
628  */
629 void
630 GNUNET_CRYPTO_short_hash (const void *block, size_t size, 
631                           struct GNUNET_CRYPTO_ShortHashCode * ret);
632
633
634 /**
635  * Double short (256-bit) hash to create a long hash.
636  *
637  * @param sh short hash to double
638  * @param dh where to store the (doubled) long hash (not really a hash)
639  */
640 void
641 GNUNET_CRYPTO_short_hash_double (const struct GNUNET_CRYPTO_ShortHashCode *sh,
642                                  struct GNUNET_HashCode *dh);
643
644
645 /**
646  * Truncate doubled short hash back to a short hash.
647  *
648  * @param dh doubled short hash to reduce again
649  * @param sh where to store the short hash
650  * @return GNUNET_OK on success, GNUNET_SYSERR if this was not a
651  *         doubled short hash
652  */
653 int
654 GNUNET_CRYPTO_short_hash_from_truncation (const struct GNUNET_HashCode *dh,
655                                           struct GNUNET_CRYPTO_ShortHashCode *sh);
656
657
658 /**
659  * Calculate HMAC of a message (RFC 2104)
660  *
661  * @param key secret key
662  * @param plaintext input plaintext
663  * @param plaintext_len length of plaintext
664  * @param hmac where to store the hmac
665  */
666 void
667 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
668                     const void *plaintext, size_t plaintext_len,
669                     struct GNUNET_HashCode * hmac);
670
671
672 /**
673  * Function called once the hash computation over the
674  * specified file has completed.
675  *
676  * @param cls closure
677  * @param res resulting hash, NULL on error
678  */
679 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
680                                                      const struct GNUNET_HashCode *
681                                                      res);
682
683
684 /**
685  * Handle to file hashing operation.
686  */
687 struct GNUNET_CRYPTO_FileHashContext;
688
689 /**
690  * Compute the hash of an entire file.
691  *
692  * @param priority scheduling priority to use
693  * @param filename name of file to hash
694  * @param blocksize number of bytes to process in one task
695  * @param callback function to call upon completion
696  * @param callback_cls closure for callback
697  * @return NULL on (immediate) errror
698  */
699 struct GNUNET_CRYPTO_FileHashContext *
700 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
701                          const char *filename, size_t blocksize,
702                          GNUNET_CRYPTO_HashCompletedCallback callback,
703                          void *callback_cls);
704
705
706 /**
707  * Cancel a file hashing operation.
708  *
709  * @param fhc operation to cancel (callback must not yet have been invoked)
710  */
711 void
712 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
713
714
715 /**
716  * Create a random hash code.
717  *
718  * @param mode desired quality level
719  * @param result hash code that is randomized
720  */
721 void
722 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
723                                   struct GNUNET_HashCode * result);
724
725
726 /**
727  * compute result(delta) = b - a
728  *
729  * @param a some hash code
730  * @param b some hash code
731  * @param result set to b - a
732  */
733 void
734 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode * a,
735                                const struct GNUNET_HashCode * b,
736                                struct GNUNET_HashCode * result);
737
738
739 /**
740  * compute result(b) = a + delta
741  *
742  * @param a some hash code
743  * @param delta some hash code
744  * @param result set to a + delta
745  */
746 void
747 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode * a,
748                         const struct GNUNET_HashCode * delta,
749                         struct GNUNET_HashCode * result);
750
751
752 /**
753  * compute result = a ^ b
754  *
755  * @param a some hash code
756  * @param b some hash code
757  * @param result set to a ^ b
758  */
759 void
760 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode * a, const struct GNUNET_HashCode * b,
761                         struct GNUNET_HashCode * result);
762
763
764 /**
765  * Convert a hashcode into a key.
766  *
767  * @param hc hash code that serves to generate the key
768  * @param skey set to a valid session key
769  * @param iv set to a valid initialization vector
770  */
771 void
772 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
773                                struct GNUNET_CRYPTO_AesSessionKey *skey,
774                                struct GNUNET_CRYPTO_AesInitializationVector
775                                *iv);
776
777
778 /**
779  * Obtain a bit from a hashcode.
780  *
781  * @param code the GNUNET_CRYPTO_hash to index bit-wise
782  * @param bit index into the hashcode, [0...159]
783  * @return Bit \a bit from hashcode \a code, -1 for invalid index
784  */
785 int
786 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode * code, unsigned int bit);
787
788 /**
789  * Determine how many low order bits match in two
790  * struct GNUNET_HashCodes.  i.e. - 010011 and 011111 share
791  * the first two lowest order bits, and therefore the
792  * return value is two (NOT XOR distance, nor how many
793  * bits match absolutely!).
794  *
795  * @param first the first hashcode
796  * @param second the hashcode to compare first to
797  *
798  * @return the number of bits that match
799  */
800 unsigned int
801 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode * first,
802                                   const struct GNUNET_HashCode * second);
803
804
805 /**
806  * Compare function for HashCodes, producing a total ordering
807  * of all hashcodes.
808  *
809  * @param h1 some hash code
810  * @param h2 some hash code
811  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
812  */
813 int
814 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode * h1, const struct GNUNET_HashCode * h2);
815
816
817 /**
818  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
819  * in the XOR metric (Kademlia).
820  *
821  * @param h1 some hash code
822  * @param h2 some hash code
823  * @param target some hash code
824  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
825  */
826 int
827 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode * h1,
828                            const struct GNUNET_HashCode * h2,
829                            const struct GNUNET_HashCode * target);
830
831
832 /**
833  * @brief Derive an authentication key
834  * @param key authentication key
835  * @param rkey root key
836  * @param salt salt
837  * @param salt_len size of the salt
838  * @param argp pair of void * & size_t for context chunks, terminated by NULL
839  */
840 void
841 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
842                                  const struct GNUNET_CRYPTO_AesSessionKey *rkey,
843                                  const void *salt, size_t salt_len,
844                                  va_list argp);
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 ... pair of void * & size_t for context chunks, terminated by NULL
854  */
855 void
856 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
857                                const struct GNUNET_CRYPTO_AesSessionKey *rkey,
858                                const void *salt, size_t salt_len, ...);
859
860 /**
861  * @brief Derive key
862  * @param result buffer for the derived key, allocated by caller
863  * @param out_len desired length of the derived key
864  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
865  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
866  * @param xts salt
867  * @param xts_len length of xts
868  * @param skm source key material
869  * @param skm_len length of skm
870  * @param ... pair of void * & size_t for context chunks, terminated by NULL
871  * @return GNUNET_YES on success
872  */
873 int
874 GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo, int prf_algo,
875                     const void *xts, size_t xts_len, const void *skm,
876                     size_t skm_len, ...);
877
878
879 /**
880  * @brief Derive key
881  * @param result buffer for the derived key, allocated by caller
882  * @param out_len desired length of the derived key
883  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
884  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
885  * @param xts salt
886  * @param xts_len length of xts
887  * @param skm source key material
888  * @param skm_len length of skm
889  * @param argp va_list of void * & size_t pairs for context chunks
890  * @return GNUNET_YES on success
891  */
892 int
893 GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
894                       const void *xts, size_t xts_len, const void *skm,
895                       size_t skm_len, va_list argp);
896
897
898 /**
899  * @brief Derive key
900  * @param result buffer for the derived key, allocated by caller
901  * @param out_len desired length of the derived key
902  * @param xts salt
903  * @param xts_len length of xts
904  * @param skm source key material
905  * @param skm_len length of skm
906  * @param argp va_list of void * & size_t pairs for context chunks
907  * @return GNUNET_YES on success
908  */
909 int
910 GNUNET_CRYPTO_kdf_v (void *result, size_t out_len, const void *xts,
911                      size_t xts_len, const void *skm, size_t skm_len,
912                      va_list argp);
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 xts salt
920  * @param xts_len length of xts
921  * @param skm source key material
922  * @param skm_len length of skm
923  * @param ... void * & size_t pairs for context chunks
924  * @return GNUNET_YES on success
925  */
926 int
927 GNUNET_CRYPTO_kdf (void *result, size_t out_len, const void *xts,
928                    size_t xts_len, const void *skm, size_t skm_len, ...);
929
930
931 /**
932  * Convert a public key to a string.
933  *
934  * @param pub key to convert
935  * @return string representing  'pub'
936  */
937 char *
938 GNUNET_CRYPTO_rsa_public_key_to_string (const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub);
939
940
941 /**
942  * Convert a string representing a public key to a public key.
943  *
944  * @param enc encoded public key
945  * @param enclen number of bytes in enc (without 0-terminator)
946  * @param pub where to store the public key
947  * @return GNUNET_OK on success
948  */
949 int
950 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc, 
951                                           size_t enclen,
952                                           struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub);
953
954
955 /**
956  * Encode the private key in a format suitable for
957  * storing it into a file.
958  * @return encoding of the private key
959  */
960 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
961 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
962
963
964 /**
965  * Decode the private key from the data-format back
966  * to the "normal", internal format.
967  *
968  * @param buf the buffer where the private key data is stored
969  * @param len the length of the data in 'buffer'
970  * @return NULL on error
971  */
972 struct GNUNET_CRYPTO_RsaPrivateKey *
973 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len);
974
975
976 /**
977  * Create a new private key by reading it from a file.  If the
978  * files does not exist, create a new key and write it to the
979  * file.  Caller must free return value. Note that this function
980  * can not guarantee that another process might not be trying
981  * the same operation on the same file at the same time.
982  * If the contents of the file
983  * are invalid the old file is deleted and a fresh key is
984  * created.
985  *
986  * @param filename name of file to use for storage
987  * @return new private key, NULL on error (for example,
988  *   permission denied)
989  * @deprecated use 'GNUNET_CRYPTO_rsa_key_create_start' instead
990  */
991 struct GNUNET_CRYPTO_RsaPrivateKey *
992 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
993
994
995 /**
996  * Open existing private key file and read it.  If the
997  * file does not exist, or the contents of the file are
998  * invalid, the function fails
999  * Caller must free returned value.
1000  *
1001  * @return a private key, NULL on error (for example,
1002  *         permission denied) or when file does not exist or contains invalid
1003  *         data.
1004  */
1005 struct GNUNET_CRYPTO_RsaPrivateKey *
1006 GNUNET_CRYPTO_rsa_key_create_from_existing_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  * Get hash of the public key that corresponds to a private key.
1100  *
1101  * @param key RSA private key
1102  * @param id buffer for hash of the public key
1103  */
1104 void
1105 GNUNET_CRYPTO_rsa_get_public_key_hash (struct GNUNET_CRYPTO_RsaPrivateKey *key,
1106     struct GNUNET_HashCode *id);
1107
1108
1109 /**
1110  * Encrypt a block with the public key of another host that uses the
1111  * same cyper.
1112  *
1113  * @param block the block to encrypt
1114  * @param size the size of block
1115  * @param publicKey the encoded public key used to encrypt
1116  * @param target where to store the encrypted block
1117  * @return GNUNET_SYSERR on error, GNUNET_OK if ok
1118  */
1119 int
1120 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
1121                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1122                            *publicKey,
1123                            struct GNUNET_CRYPTO_RsaEncryptedData *target);
1124
1125
1126 /**
1127  * Decrypt a given block with the hostkey.
1128  *
1129  * @param key the key to use
1130  * @param block the data to decrypt, encoded as returned by encrypt, not consumed
1131  * @param result pointer to a location where the result can be stored
1132  * @param max how many bytes of a result are expected? Must be exact.
1133  * @return the size of the decrypted block (that is, size) or -1 on error
1134  */
1135 ssize_t
1136 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1137                            const struct GNUNET_CRYPTO_RsaEncryptedData *block,
1138                            void *result, size_t max);
1139
1140
1141 /**
1142  * Sign a given block.
1143  *
1144  * @param key private key to use for the signing
1145  * @param purpose what to sign (size, purpose)
1146  * @param sig where to write the signature
1147  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1148  */
1149 int
1150 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1151                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
1152                         struct GNUNET_CRYPTO_RsaSignature *sig);
1153
1154
1155 /**
1156  * Verify signature.  Note that the caller MUST have already
1157  * checked that "validate->size" bytes are actually available.
1158  *
1159  * @param purpose what is the purpose that validate should have?
1160  * @param validate block to validate (size, purpose, data)
1161  * @param sig signature that is being validated
1162  * @param publicKey public key of the signer
1163  * @return GNUNET_OK if ok, GNUNET_SYSERR if invalid
1164  */
1165 int
1166 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
1167                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
1168                           *validate,
1169                           const struct GNUNET_CRYPTO_RsaSignature *sig,
1170                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
1171                           *publicKey);
1172
1173
1174
1175 /**
1176  * Function called upon completion of 'GNUNET_CRYPTO_ecc_key_create_async'.
1177  *
1178  * @param cls closure
1179  * @param pk NULL on error, otherwise the private key (which must be free'd by the callee)
1180  * @param emsg NULL on success, otherwise an error message
1181  */
1182 typedef void (*GNUNET_CRYPTO_EccKeyCallback)(void *cls,
1183                                              struct GNUNET_CRYPTO_EccPrivateKey *pk,
1184                                              const char *emsg);
1185
1186
1187 /**
1188  * Free memory occupied by ECC key
1189  *
1190  * @param privatekey pointer to the memory to free
1191  */
1192 void
1193 GNUNET_CRYPTO_ecc_key_free (struct GNUNET_CRYPTO_EccPrivateKey *privatekey);
1194
1195
1196 /**
1197  * Extract the public key for the given private key.
1198  *
1199  * @param priv the private key
1200  * @param pub where to write the public key
1201  */
1202 void
1203 GNUNET_CRYPTO_ecc_key_get_public (const struct GNUNET_CRYPTO_EccPrivateKey *priv,
1204                                   struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub);
1205
1206 /**
1207  * Convert a public key to a string.
1208  *
1209  * @param pub key to convert
1210  * @return string representing  'pub'
1211  */
1212 char *
1213 GNUNET_CRYPTO_ecc_public_key_to_string (const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub);
1214
1215
1216 /**
1217  * Convert a string representing a public key to a public key.
1218  *
1219  * @param enc encoded public key
1220  * @param enclen number of bytes in enc (without 0-terminator)
1221  * @param pub where to store the public key
1222  * @return GNUNET_OK on success
1223  */
1224 int
1225 GNUNET_CRYPTO_ecc_public_key_from_string (const char *enc, 
1226                                           size_t enclen,
1227                                           struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub);
1228
1229
1230 /**
1231  * Encode the private key in a format suitable for
1232  * storing it into a file.
1233  *
1234  * @param key key to encode
1235  * @return encoding of the private key.
1236  *    The first 4 bytes give the size of the array, as usual.
1237  */
1238 struct GNUNET_CRYPTO_EccPrivateKeyBinaryEncoded *
1239 GNUNET_CRYPTO_ecc_encode_key (const struct GNUNET_CRYPTO_EccPrivateKey *key);
1240
1241
1242 /**
1243  * Decode the private key from the file-format back
1244  * to the "normal", internal format.
1245  *
1246  * @param buf the buffer where the private key data is stored
1247  * @param len the length of the data in 'buffer'
1248  * @param validate GNUNET_YES to validate that the key is well-formed,
1249  *                 GNUNET_NO if the key comes from a totally trusted source 
1250  *                 and validation is considered too expensive
1251  * @return NULL on error
1252  */
1253 struct GNUNET_CRYPTO_EccPrivateKey *
1254 GNUNET_CRYPTO_ecc_decode_key (const char *buf, 
1255                               size_t len,
1256                               int validate);
1257
1258
1259 /**
1260  * Create a new private key by reading it from a file.  If the
1261  * files does not exist, create a new key and write it to the
1262  * file.  Caller must free return value.  Note that this function
1263  * can not guarantee that another process might not be trying
1264  * the same operation on the same file at the same time.
1265  * If the contents of the file
1266  * are invalid the old file is deleted and a fresh key is
1267  * created.
1268  *
1269  * @return new private key, NULL on error (for example,
1270  *   permission denied)
1271  */
1272 struct GNUNET_CRYPTO_EccPrivateKey *
1273 GNUNET_CRYPTO_ecc_key_create_from_file (const char *filename);
1274
1275
1276 /**
1277  * Handle to cancel private key generation and state for the
1278  * key generation operation.
1279  */
1280 struct GNUNET_CRYPTO_EccKeyGenerationContext;
1281
1282 /**
1283  * Create a new private key. Caller must free return value.  Blocking version
1284  * (blocks to gather entropy).
1285  *
1286  * @return fresh private key
1287  */
1288 struct GNUNET_CRYPTO_EccPrivateKey *
1289 GNUNET_CRYPTO_ecc_key_create (void);
1290
1291
1292 /**
1293  * Create a new private key by reading it from a file.  If the files
1294  * does not exist, create a new key and write it to the file.  If the
1295  * contents of the file are invalid the old file is deleted and a
1296  * fresh key is created.
1297  *
1298  * @param filename name of file to use for storage
1299  * @param cont function to call when done (or on errors)
1300  * @param cont_cls closure for 'cont'
1301  * @return handle to abort operation, NULL on fatal errors (cont will not be called if NULL is returned)
1302  */
1303 struct GNUNET_CRYPTO_EccKeyGenerationContext *
1304 GNUNET_CRYPTO_ecc_key_create_start (const char *filename,
1305                                     GNUNET_CRYPTO_EccKeyCallback cont,
1306                                     void *cont_cls);
1307
1308
1309 /**
1310  * Abort ECC key generation.
1311  *
1312  * @param gc key generation context to abort
1313  */
1314 void
1315 GNUNET_CRYPTO_ecc_key_create_stop (struct GNUNET_CRYPTO_EccKeyGenerationContext *gc);
1316
1317 /**
1318  * Setup a hostkey file for a peer given the name of the
1319  * configuration file (!).  This function is used so that
1320  * at a later point code can be certain that reading a
1321  * hostkey is fast (for example in time-dependent testcases).
1322  *
1323  * @param cfg_name name of the configuration file to use
1324  */
1325 void
1326 GNUNET_CRYPTO_ecc_setup_hostkey (const char *cfg_name);
1327
1328
1329 /**
1330  * Retrieve the identity of the host's peer.
1331  *
1332  * @param cfg configuration to use
1333  * @param dst pointer to where to write the peer identity
1334  * @return GNUNET_OK on success, GNUNET_SYSERR if the identity
1335  *         could not be retrieved
1336  */
1337 int
1338 GNUNET_CRYPTO_get_host_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
1339                                  struct GNUNET_PeerIdentity *dst);
1340
1341
1342 /**
1343  * Derive key material from a public and a private ECC key.
1344  *
1345  * @param key private key to use for the ECDH (x)
1346  * @param pub public key to use for the ECDY (yG)
1347  * @param key_material where to write the key material (xyG)
1348  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1349  */
1350 int
1351 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1352                         const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded *pub,
1353                         struct GNUNET_HashCode *key_material);
1354
1355
1356 /**
1357  * Sign a given block.
1358  *
1359  * @param key private key to use for the signing
1360  * @param purpose what to sign (size, purpose)
1361  * @param sig where to write the signature
1362  * @return GNUNET_SYSERR on error, GNUNET_OK on success
1363  */
1364 int
1365 GNUNET_CRYPTO_ecc_sign (const struct GNUNET_CRYPTO_EccPrivateKey *key,
1366                         const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1367                         struct GNUNET_CRYPTO_EccSignature *sig);
1368
1369
1370 /**
1371  * Verify signature.
1372  *
1373  * @param purpose what is the purpose that the signature should have?
1374  * @param validate block to validate (size, purpose, data)
1375  * @param sig signature that is being validated
1376  * @param publicKey public key of the signer
1377  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
1378  */
1379 int
1380 GNUNET_CRYPTO_ecc_verify (uint32_t purpose,
1381                           const struct GNUNET_CRYPTO_EccSignaturePurpose
1382                           *validate,
1383                           const struct GNUNET_CRYPTO_EccSignature *sig,
1384                           const struct GNUNET_CRYPTO_EccPublicKeyBinaryEncoded
1385                           *publicKey);
1386
1387
1388 #if 0                           /* keep Emacsens' auto-indent happy */
1389 {
1390 #endif
1391 #ifdef __cplusplus
1392 }
1393 #endif
1394
1395
1396 /* ifndef GNUNET_CRYPTO_LIB_H */
1397 #endif
1398 /* end of gnunet_crypto_lib.h */