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