6224546b92d08e2358c6a3ad48a966f1fb7f8189
[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 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file include/gnunet_crypto_lib.h
23  * @brief cryptographic primitives for GNUnet
24  *
25  * @author Christian Grothoff
26  * @author Krista Bennett
27  * @author Gerd Knorr <kraxel@bytesex.org>
28  * @author Ioana Patrascu
29  * @author Tzvetan Horozov
30  */
31
32 #ifndef GNUNET_CRYPTO_LIB_H
33 #define GNUNET_CRYPTO_LIB_H
34
35 #ifdef __cplusplus
36 extern "C"
37 {
38 #if 0                           /* keep Emacsens' auto-indent happy */
39 }
40 #endif
41 #endif
42
43 #include "gnunet_common.h"
44 #include "gnunet_scheduler_lib.h"
45
46 /**
47  * Desired quality level for cryptographic operations.
48  */
49 enum GNUNET_CRYPTO_Quality
50 {
51   /**
52    * No good quality of the operation is needed (i.e.,
53    * random numbers can be pseudo-random).
54    */
55   GNUNET_CRYPTO_QUALITY_WEAK,
56
57   /**
58    * High-quality operations are desired.
59    */
60   GNUNET_CRYPTO_QUALITY_STRONG,
61
62   /**
63    * Randomness for IVs etc. is required.
64    */
65   GNUNET_CRYPTO_QUALITY_NONCE
66 };
67
68
69 /**
70  * @brief length of the sessionkey in bytes (256 BIT sessionkey)
71  */
72 #define GNUNET_CRYPTO_AES_KEY_LENGTH (256/8)
73
74
75 /**
76  * @brief Length of RSA encrypted data (2048 bit)
77  *
78  * We currently do not handle encryption of data
79  * that can not be done in a single call to the
80  * RSA methods (read: large chunks of data).
81  * We should never need that, as we can use
82  * the GNUNET_CRYPTO_hash for larger pieces of data for signing,
83  * and for encryption, we only need to encode sessionkeys!
84  */
85 #define GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH 256
86
87
88 /**
89  * Length of an RSA KEY (n,e,len), 2048 bit (=256 octests) key n, 2 byte e
90  */
91 #define GNUNET_CRYPTO_RSA_KEY_LENGTH 258
92
93
94 /**
95  * Length of a hash value
96  */
97 #define GNUNET_CRYPTO_HASH_LENGTH 512/8
98
99 /**
100  * The private information of an RSA key pair.
101  */
102 struct GNUNET_CRYPTO_RsaPrivateKey;
103
104 GNUNET_NETWORK_STRUCT_BEGIN
105
106 /**
107  * GNUnet mandates a certain format for the encoding
108  * of private RSA key information that is provided
109  * by the RSA implementations.  This format is used
110  * to serialize a private RSA key (typically when
111  * writing it to disk).
112  */
113 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded
114 {
115   /**
116    * Total size of the structure, in bytes, in big-endian!
117    */
118   uint16_t len GNUNET_PACKED;
119   uint16_t sizen GNUNET_PACKED; /*  in big-endian! */
120   uint16_t sizee GNUNET_PACKED; /*  in big-endian! */
121   uint16_t sized GNUNET_PACKED; /*  in big-endian! */
122   uint16_t sizep GNUNET_PACKED; /*  in big-endian! */
123   uint16_t sizeq GNUNET_PACKED; /*  in big-endian! */
124   uint16_t sizedmp1 GNUNET_PACKED;      /*  in big-endian! */
125   uint16_t sizedmq1 GNUNET_PACKED;      /*  in big-endian! */
126   /* followed by the actual values */
127 };
128 GNUNET_NETWORK_STRUCT_END
129
130
131 /**
132  * @brief 0-terminated ASCII encoding of a GNUNET_HashCode.
133  */
134 struct GNUNET_CRYPTO_HashAsciiEncoded
135 {
136   unsigned char encoding[104];
137 };
138
139
140
141 /**
142  * @brief an RSA signature
143  */
144 struct GNUNET_CRYPTO_RsaSignature
145 {
146   unsigned char sig[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
147 };
148
149
150 GNUNET_NETWORK_STRUCT_BEGIN
151
152 /**
153  * @brief header of what an RSA signature signs
154  *        this must be followed by "size - 8" bytes of
155  *        the actual signed data
156  */
157 struct GNUNET_CRYPTO_RsaSignaturePurpose
158 {
159   /**
160    * How many bytes does this signature sign?
161    * (including this purpose header); in network
162    * byte order (!).
163    */
164   uint32_t size GNUNET_PACKED;
165
166   /**
167    * What does this signature vouch for?  This
168    * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
169    * constant (from gnunet_signatures.h).  In
170    * network byte order!
171    */
172   uint32_t purpose GNUNET_PACKED;
173
174 };
175
176
177 /**
178  * @brief A public key.
179  */
180 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
181 {
182   /**
183    * In big-endian, must be GNUNET_CRYPTO_RSA_KEY_LENGTH+4
184    */
185   uint16_t len GNUNET_PACKED;
186
187   /**
188    * Size of n in key; in big-endian!
189    */
190   uint16_t sizen GNUNET_PACKED;
191
192   /**
193    * The key itself, contains n followed by e.
194    */
195   unsigned char key[GNUNET_CRYPTO_RSA_KEY_LENGTH];
196
197   /**
198    * Padding (must be 0)
199    */
200   uint16_t padding GNUNET_PACKED;
201 };
202
203
204 /**
205  * RSA Encrypted data.
206  */
207 struct GNUNET_CRYPTO_RsaEncryptedData
208 {
209   unsigned char encoding[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
210 };
211
212
213 /**
214  * @brief type for session keys
215  */
216 struct GNUNET_CRYPTO_AesSessionKey
217 {
218   /**
219    * Actual key.
220    */
221   unsigned char key[GNUNET_CRYPTO_AES_KEY_LENGTH];
222
223   /**
224    * checksum!
225    */
226   uint32_t crc32 GNUNET_PACKED;
227 };
228 GNUNET_NETWORK_STRUCT_END
229
230 /**
231  * @brief IV for sym cipher
232  *
233  * NOTE: must be smaller (!) in size than the
234  * GNUNET_HashCode.
235  */
236 struct GNUNET_CRYPTO_AesInitializationVector
237 {
238   unsigned char iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
239 };
240
241
242 /**
243  * @brief type for (message) authentication keys
244  */
245 struct GNUNET_CRYPTO_AuthKey
246 {
247   unsigned char key[GNUNET_CRYPTO_HASH_LENGTH];
248 };
249
250
251 /* **************** Functions and Macros ************* */
252
253 /**
254  * Seed a weak random generator. Only GNUNET_CRYPTO_QUALITY_WEAK-mode generator
255  * can be seeded.
256  *
257  * @param seed the seed to use
258  */
259 void
260 GNUNET_CRYPTO_seed_weak_random (int32_t seed);
261
262
263 /**
264  * Perform an incremental step in a CRC16 (for TCP/IP) calculation.
265  *
266  * @param sum current sum, initially 0
267  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
268  * @param len number of bytes in hdr, must be multiple of 2
269  * @return updated crc sum (must be subjected to GNUNET_CRYPTO_crc16_finish to get actual crc16)
270  */
271 uint32_t
272 GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len);
273
274
275 /**
276  * Convert results from GNUNET_CRYPTO_crc16_step to final crc16.
277  *
278  * @param sum cummulative sum
279  * @return crc16 value
280  */
281 uint16_t
282 GNUNET_CRYPTO_crc16_finish (uint32_t sum);
283
284
285 /**
286  * Calculate the checksum of a buffer in one step.
287  *
288  * @param buf buffer to  calculate CRC over (must be 16-bit aligned)
289  * @param len number of bytes in hdr, must be multiple of 2
290  * @return crc16 value
291  */
292 uint16_t
293 GNUNET_CRYPTO_crc16_n (const void *buf, size_t len);
294
295
296 /**
297  * Compute the CRC32 checksum for the first len
298  * bytes of the buffer.
299  *
300  * @param buf the data over which we're taking the CRC
301  * @param len the length of the buffer in bytes
302  * @return the resulting CRC32 checksum
303  */
304 int32_t
305 GNUNET_CRYPTO_crc32_n (const void *buf, size_t len);
306
307
308 /**
309  * Produce a random value.
310  *
311  * @param mode desired quality of the random number
312  * @param i the upper limit (exclusive) for the random number
313  * @return a random value in the interval [0,i) (exclusive).
314  */
315 uint32_t
316 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i);
317
318
319 /**
320  * Random on unsigned 64-bit values.
321  *
322  * @param mode desired quality of the random number
323  * @param max value returned will be in range [0,max) (exclusive)
324  * @return random 64-bit number
325  */
326 uint64_t
327 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max);
328
329
330 /**
331  * Get an array with a random permutation of the
332  * numbers 0...n-1.
333  * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
334  * @param n the size of the array
335  * @return the permutation array (allocated from heap)
336  */
337 unsigned int *
338 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n);
339
340
341 /**
342  * Create a new Session key.
343  *
344  * @param key key to initialize
345  */
346 void
347 GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey *key);
348
349
350 /**
351  * Check that a new session key is well-formed.
352  *
353  * @param key key to check
354  * @return GNUNET_OK if the key is valid
355  */
356 int
357 GNUNET_CRYPTO_aes_check_session_key (const struct GNUNET_CRYPTO_AesSessionKey
358                                      *key);
359
360
361 /**
362  * Encrypt a block with the public key of another
363  * host that uses the same cyper.
364  *
365  * @param block the block to encrypt
366  * @param len the size of the block
367  * @param sessionkey the key used to encrypt
368  * @param iv the initialization vector to use, use INITVALUE
369  *        for streams.
370  * @return the size of the encrypted block, -1 for errors
371  */
372 ssize_t
373 GNUNET_CRYPTO_aes_encrypt (const void *block, size_t len,
374                            const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
375                            const struct GNUNET_CRYPTO_AesInitializationVector
376                            *iv, void *result);
377
378
379 /**
380  * Decrypt a given block with the sessionkey.
381  *
382  * @param block the data to decrypt, encoded as returned by encrypt
383  * @param size how big is the block?
384  * @param sessionkey the key used to decrypt
385  * @param iv the initialization vector to use
386  * @param result address to store the result at
387  * @return -1 on failure, size of decrypted block on success
388  */
389 ssize_t
390 GNUNET_CRYPTO_aes_decrypt (const void *block, size_t size,
391                            const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
392                            const struct GNUNET_CRYPTO_AesInitializationVector
393                            *iv, void *result);
394
395
396 /**
397  * @brief Derive an IV
398  * @param iv initialization vector
399  * @param skey session key
400  * @param salt salt for the derivation
401  * @param salt_len size of the salt
402  * @param ... pairs of void * & size_t for context chunks, terminated by NULL
403  */
404 void
405 GNUNET_CRYPTO_aes_derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
406                              const struct GNUNET_CRYPTO_AesSessionKey *skey,
407                              const void *salt, size_t salt_len, ...);
408
409
410 /**
411  * @brief Derive an IV
412  * @param iv initialization vector
413  * @param skey session key
414  * @param salt salt for the derivation
415  * @param salt_len size of the salt
416  * @param argp pairs of void * & size_t for context chunks, terminated by NULL
417  */
418 void
419 GNUNET_CRYPTO_aes_derive_iv_v (struct GNUNET_CRYPTO_AesInitializationVector *iv,
420                                const struct GNUNET_CRYPTO_AesSessionKey *skey,
421                                const void *salt, size_t salt_len, va_list argp);
422
423
424 /**
425  * Convert hash to ASCII encoding.
426  * @param block the hash code
427  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
428  *  safely cast to char*, a '\\0' termination is set).
429  */
430 void
431 GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
432                            struct GNUNET_CRYPTO_HashAsciiEncoded *result);
433
434
435 /**
436  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
437  *
438  * @param enc the encoding
439  * @param enclen number of characters in 'enc' (without 0-terminator, which can be missing)
440  * @param result where to store the GNUNET_CRYPTO_hash code
441  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
442  */
443 int
444 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
445                                  GNUNET_HashCode * result);
446
447
448 /**
449  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
450  * @param enc the encoding
451  * @param result where to store the GNUNET_CRYPTO_hash code
452  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
453  */
454 #define GNUNET_CRYPTO_hash_from_string(enc, result) \
455   GNUNET_CRYPTO_hash_from_string2 (enc, strlen(enc), result)
456
457
458 /**
459  * Compute the distance between 2 hashcodes.
460  * The computation must be fast, not involve
461  * a.a or a.e (they're used elsewhere), and
462  * be somewhat consistent. And of course, the
463  * result should be a positive number.
464  *
465  * @param a some hash code
466  * @param b some hash code
467  * @return number between 0 and UINT32_MAX
468  */
469 uint32_t
470 GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
471                                  const GNUNET_HashCode * b);
472
473
474 /**
475  * Compute hash of a given block.
476  *
477  * @param block the data to hash
478  * @param size size of the block
479  * @param ret pointer to where to write the hashcode
480  */
481 void
482 GNUNET_CRYPTO_hash (const void *block, size_t size, GNUNET_HashCode * ret);
483
484
485 /**
486  * Calculate HMAC of a message (RFC 2104)
487  *
488  * @param key secret key
489  * @param plaintext input plaintext
490  * @param plaintext_len length of plaintext
491  * @param hmac where to store the hmac
492  */
493 void
494 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
495                     const void *plaintext, size_t plaintext_len,
496                     GNUNET_HashCode * hmac);
497
498
499 /**
500  * Function called once the hash computation over the
501  * specified file has completed.
502  *
503  * @param cls closure
504  * @param res resulting hash, NULL on error
505  */
506 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
507                                                      const GNUNET_HashCode *
508                                                      res);
509
510
511 /**
512  * Handle to file hashing operation.
513  */
514 struct GNUNET_CRYPTO_FileHashContext;
515
516 /**
517  * Compute the hash of an entire file.
518  *
519  * @param priority scheduling priority to use
520  * @param filename name of file to hash
521  * @param blocksize number of bytes to process in one task
522  * @param callback function to call upon completion
523  * @param callback_cls closure for callback
524  * @return NULL on (immediate) errror
525  */
526 struct GNUNET_CRYPTO_FileHashContext *
527 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
528                          const char *filename, size_t blocksize,
529                          GNUNET_CRYPTO_HashCompletedCallback callback,
530                          void *callback_cls);
531
532
533 /**
534  * Cancel a file hashing operation.
535  *
536  * @param fhc operation to cancel (callback must not yet have been invoked)
537  */
538 void
539 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
540
541
542 /**
543  * Create a random hash code.
544  *
545  * @param mode desired quality level
546  * @param result hash code that is randomized
547  */
548 void
549 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
550                                   GNUNET_HashCode * result);
551
552
553 /**
554  * compute result(delta) = b - a
555  *
556  * @param a some hash code
557  * @param b some hash code
558  * @param result set to b - a
559  */
560 void
561 GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
562                                const GNUNET_HashCode * b,
563                                GNUNET_HashCode * result);
564
565
566 /**
567  * compute result(b) = a + delta
568  *
569  * @param a some hash code
570  * @param delta some hash code
571  * @param result set to a + delta
572  */
573 void
574 GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
575                         const GNUNET_HashCode * delta,
576                         GNUNET_HashCode * result);
577
578
579 /**
580  * compute result = a ^ b
581  *
582  * @param a some hash code
583  * @param b some hash code
584  * @param result set to a ^ b
585  */
586 void
587 GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a, const GNUNET_HashCode * b,
588                         GNUNET_HashCode * result);
589
590
591 /**
592  * Convert a hashcode into a key.
593  *
594  * @param hc hash code that serves to generate the key
595  * @param skey set to a valid session key
596  * @param iv set to a valid initialization vector
597  */
598 void
599 GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
600                                struct GNUNET_CRYPTO_AesSessionKey *skey,
601                                struct GNUNET_CRYPTO_AesInitializationVector
602                                *iv);
603
604
605 /**
606  * Obtain a bit from a hashcode.
607  *
608  * @param code the GNUNET_CRYPTO_hash to index bit-wise
609  * @param bit index into the hashcode, [0...159]
610  * @return Bit \a bit from hashcode \a code, -1 for invalid index
611  */
612 int
613 GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code, unsigned int bit);
614
615 /**
616  * Determine how many low order bits match in two
617  * GNUNET_HashCodes.  i.e. - 010011 and 011111 share
618  * the first two lowest order bits, and therefore the
619  * return value is two (NOT XOR distance, nor how many
620  * bits match absolutely!).
621  *
622  * @param first the first hashcode
623  * @param second the hashcode to compare first to
624  *
625  * @return the number of bits that match
626  */
627 unsigned int
628 GNUNET_CRYPTO_hash_matching_bits (const GNUNET_HashCode * first,
629                                   const GNUNET_HashCode * second);
630
631
632 /**
633  * Compare function for HashCodes, producing a total ordering
634  * of all hashcodes.
635  *
636  * @param h1 some hash code
637  * @param h2 some hash code
638  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
639  */
640 int
641 GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1, const GNUNET_HashCode * h2);
642
643
644 /**
645  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
646  * in the XOR metric (Kademlia).
647  *
648  * @param h1 some hash code
649  * @param h2 some hash code
650  * @param target some hash code
651  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
652  */
653 int
654 GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
655                            const GNUNET_HashCode * h2,
656                            const GNUNET_HashCode * target);
657
658
659 /**
660  * @brief Derive an authentication key
661  * @param key authentication key
662  * @param rkey root key
663  * @param salt salt
664  * @param salt_len size of the salt
665  * @param argp pair of void * & size_t for context chunks, terminated by NULL
666  */
667 void
668 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
669                                  const struct GNUNET_CRYPTO_AesSessionKey *rkey,
670                                  const void *salt, size_t salt_len,
671                                  va_list argp);
672
673
674 /**
675  * @brief Derive an authentication key
676  * @param key authentication key
677  * @param rkey root key
678  * @param salt salt
679  * @param salt_len size of the salt
680  * @param ... pair of void * & size_t for context chunks, terminated by NULL
681  */
682 void
683 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
684                                const struct GNUNET_CRYPTO_AesSessionKey *rkey,
685                                const void *salt, size_t salt_len, ...);
686
687 /**
688  * @brief Derive key
689  * @param result buffer for the derived key, allocated by caller
690  * @param out_len desired length of the derived key
691  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
692  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
693  * @param xts salt
694  * @param xts_len length of xts
695  * @param skm source key material
696  * @param skm_len length of skm
697  * @return GNUNET_YES on success
698  */
699 int
700 GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo, int prf_algo,
701                     const void *xts, size_t xts_len, const void *skm,
702                     size_t skm_len, ...);
703
704
705 /**
706  * @brief Derive key
707  * @param result buffer for the derived key, allocated by caller
708  * @param out_len desired length of the derived key
709  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
710  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
711  * @param xts salt
712  * @param xts_len length of xts
713  * @param skm source key material
714  * @param skm_len length of skm
715  * @param argp va_list of void * & size_t pairs for context chunks
716  * @return GNUNET_YES on success
717  */
718 int
719 GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
720                       const void *xts, size_t xts_len, const void *skm,
721                       size_t skm_len, va_list argp);
722
723
724 /**
725  * @brief Derive key
726  * @param result buffer for the derived key, allocated by caller
727  * @param out_len desired length of the derived key
728  * @param xts salt
729  * @param xts_len length of xts
730  * @param skm source key material
731  * @param skm_len length of skm
732  * @param argp va_list of void * & size_t pairs for context chunks
733  * @return GNUNET_YES on success
734  */
735 int
736 GNUNET_CRYPTO_kdf_v (void *result, size_t out_len, const void *xts,
737                      size_t xts_len, const void *skm, size_t skm_len,
738                      va_list argp);
739
740
741 /**
742  * @brief Derive key
743  * @param result buffer for the derived key, allocated by caller
744  * @param out_len desired length of the derived key
745  * @param xts salt
746  * @param xts_len length of xts
747  * @param skm source key material
748  * @param skm_len length of skm
749  * @param ... void * & size_t pairs for context chunks
750  * @return GNUNET_YES on success
751  */
752 int
753 GNUNET_CRYPTO_kdf (void *result, size_t out_len, const void *xts,
754                    size_t xts_len, const void *skm, size_t skm_len, ...);
755
756
757 /**
758  * Create a new private key. Caller must free return value.
759  *
760  * @return fresh private key
761  */
762 struct GNUNET_CRYPTO_RsaPrivateKey *
763 GNUNET_CRYPTO_rsa_key_create (void);
764
765
766 /**
767  * Convert a public key to a string.
768  *
769  * @param pub key to convert
770  * @return string representing  'pub'
771  */
772 char *
773 GNUNET_CRYPTO_rsa_public_key_to_string (struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub);
774
775
776 /**
777  * Convert a string representing a public key to a public key.
778  *
779  * @param enc encoded public key
780  * @param enclen number of bytes in enc (without 0-terminator)
781  * @param pub where to store the public key
782  * @return GNUNET_OK on success
783  */
784 int
785 GNUNET_CRYPTO_rsa_public_key_from_string (const char *enc, 
786                                           size_t enclen,
787                                           struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded *pub);
788
789
790 /**
791  * Encode the private key in a format suitable for
792  * storing it into a file.
793  * @returns encoding of the private key.
794  *    The first 4 bytes give the size of the array, as usual.
795  */
796 struct GNUNET_CRYPTO_RsaPrivateKeyBinaryEncoded *
797 GNUNET_CRYPTO_rsa_encode_key (const struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
798
799 /**
800  * Decode the private key from the data-format back
801  * to the "normal", internal format.
802  *
803  * @param buf the buffer where the private key data is stored
804  * @param len the length of the data in 'buffer'
805  */
806 struct GNUNET_CRYPTO_RsaPrivateKey *
807 GNUNET_CRYPTO_rsa_decode_key (const char *buf, uint16_t len);
808
809 /**
810  * Create a new private key by reading it from a file.  If the
811  * files does not exist, create a new key and write it to the
812  * file.  Caller must free return value. Note that this function
813  * can not guarantee that another process might not be trying
814  * the same operation on the same file at the same time.
815  * If the contents of the file
816  * are invalid the old file is deleted and a fresh key is
817  * created.
818  *
819  * @param filename name of file to use for storage
820  * @return new private key, NULL on error (for example,
821  *   permission denied)
822  */
823 struct GNUNET_CRYPTO_RsaPrivateKey *
824 GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
825
826
827 /**
828  * Setup a hostkey file for a peer given the name of the
829  * configuration file (!).  This function is used so that
830  * at a later point code can be certain that reading a
831  * hostkey is fast (for example in time-dependent testcases).
832  *
833  * @param cfg_name name of the configuration file to use
834  */
835 void
836 GNUNET_CRYPTO_setup_hostkey (const char *cfg_name);
837
838
839 /**
840  * Deterministically (!) create a private key using only the
841  * given HashCode as input to the PRNG.
842  *
843  * @param hc "random" input to PRNG
844  * @return some private key purely dependent on input
845  */
846 struct GNUNET_CRYPTO_RsaPrivateKey *
847 GNUNET_CRYPTO_rsa_key_create_from_hash (const GNUNET_HashCode * hc);
848
849
850 /**
851  * Free memory occupied by the private key.
852  * @param hostkey pointer to the memory to free
853  */
854 void
855 GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
856
857
858 /**
859  * Extract the public key of the host.
860  *
861  * @param priv the private key
862  * @param pub where to write the public key
863  */
864 void
865 GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
866                                   *priv,
867                                   struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
868                                   *pub);
869
870
871 /**
872  * Encrypt a block with the public key of another host that uses the
873  * same cyper.
874  *
875  * @param block the block to encrypt
876  * @param size the size of block
877  * @param publicKey the encoded public key used to encrypt
878  * @param target where to store the encrypted block
879  * @return GNUNET_SYSERR on error, GNUNET_OK if ok
880  */
881 int
882 GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
883                            const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
884                            *publicKey,
885                            struct GNUNET_CRYPTO_RsaEncryptedData *target);
886
887
888 /**
889  * Decrypt a given block with the hostkey.
890  *
891  * @param key the key to use
892  * @param block the data to decrypt, encoded as returned by encrypt, not consumed
893  * @param result pointer to a location where the result can be stored
894  * @param max how many bytes of a result are expected? Must be exact.
895  * @return the size of the decrypted block (that is, size) or -1 on error
896  */
897 ssize_t
898 GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
899                            const struct GNUNET_CRYPTO_RsaEncryptedData *block,
900                            void *result, size_t max);
901
902
903 /**
904  * Sign a given block.
905  *
906  * @param key private key to use for the signing
907  * @param purpose what to sign (size, purpose)
908  * @param sig where to write the signature
909  * @return GNUNET_SYSERR on error, GNUNET_OK on success
910  */
911 int
912 GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
913                         const struct GNUNET_CRYPTO_RsaSignaturePurpose *purpose,
914                         struct GNUNET_CRYPTO_RsaSignature *sig);
915
916
917 /**
918  * Verify signature.  Note that the caller MUST have already
919  * checked that "validate->size" bytes are actually available.
920  *
921  * @param purpose what is the purpose that validate should have?
922  * @param validate block to validate (size, purpose, data)
923  * @param sig signature that is being validated
924  * @param publicKey public key of the signer
925  * @return GNUNET_OK if ok, GNUNET_SYSERR if invalid
926  */
927 int
928 GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
929                           const struct GNUNET_CRYPTO_RsaSignaturePurpose
930                           *validate,
931                           const struct GNUNET_CRYPTO_RsaSignature *sig,
932                           const struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
933                           *publicKey);
934
935
936
937 /**
938  * This function should only be called in testcases
939  * where strong entropy gathering is not desired
940  * (for example, for hostkey generation).
941  */
942 void
943 GNUNET_CRYPTO_random_disable_entropy_gathering (void);
944
945
946 #if 0                           /* keep Emacsens' auto-indent happy */
947 {
948 #endif
949 #ifdef __cplusplus
950 }
951 #endif
952
953
954 /* ifndef GNUNET_CRYPTO_LIB_H */
955 #endif
956 /* end of gnunet_crypto_lib.h */