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