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