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