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