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