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