183231c9b3f385c517796a043188ba91da5b7499
[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  * @defgroup crypto Cryptographic operations
32  * @defgroup hash Hashing and operations on hashes
33  */
34
35 #ifndef GNUNET_CRYPTO_LIB_H
36 #define GNUNET_CRYPTO_LIB_H
37
38 #ifdef __cplusplus
39 extern "C"
40 {
41 #if 0                           /* keep Emacsens' auto-indent happy */
42 }
43 #endif
44 #endif
45
46 /**
47  * @brief A 512-bit hashcode
48  */
49 struct GNUNET_HashCode;
50
51 /**
52  * The identity of the host (wraps the signing key of the peer).
53  */
54 struct GNUNET_PeerIdentity;
55
56 #include "gnunet_common.h"
57 #include "gnunet_scheduler_lib.h"
58 #include <gcrypt.h>
59
60
61 /**
62  * @brief A 512-bit hashcode
63  */
64 struct GNUNET_HashCode
65 {
66   uint32_t bits[512 / 8 / sizeof (uint32_t)];   /* = 16 */
67 };
68
69
70 /**
71  * Maximum length of an ECC signature.
72  * Note: round up to multiple of 8 minus 2 for alignment.
73  */
74 #define GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH 126
75
76
77 /**
78  * Desired quality level for random numbers.
79  * @ingroup crypto
80  */
81 enum GNUNET_CRYPTO_Quality
82 {
83   /**
84    * No good quality of the operation is needed (i.e.,
85    * random numbers can be pseudo-random).
86    * @ingroup crypto
87    */
88   GNUNET_CRYPTO_QUALITY_WEAK,
89
90   /**
91    * High-quality operations are desired.
92    * @ingroup crypto
93    */
94   GNUNET_CRYPTO_QUALITY_STRONG,
95
96   /**
97    * Randomness for IVs etc. is required.
98    * @ingroup crypto
99    */
100   GNUNET_CRYPTO_QUALITY_NONCE
101 };
102
103
104 /**
105  * @brief length of the sessionkey in bytes (256 BIT sessionkey)
106  */
107 #define GNUNET_CRYPTO_AES_KEY_LENGTH (256/8)
108
109 /**
110  * Length of a hash value
111  */
112 #define GNUNET_CRYPTO_HASH_LENGTH (512/8)
113
114 /**
115  * How many characters (without 0-terminator) are our ASCII-encoded
116  * public keys (ECDSA/EDDSA/ECDHE).
117  */
118 #define GNUNET_CRYPTO_PKEY_ASCII_LENGTH 52
119
120 /**
121  * @brief 0-terminated ASCII encoding of a struct GNUNET_HashCode.
122  */
123 struct GNUNET_CRYPTO_HashAsciiEncoded
124 {
125   unsigned char encoding[104];
126 };
127
128
129 GNUNET_NETWORK_STRUCT_BEGIN
130
131
132 /**
133  * @brief header of what an ECC signature signs
134  *        this must be followed by "size - 8" bytes of
135  *        the actual signed data
136  */
137 struct GNUNET_CRYPTO_EccSignaturePurpose
138 {
139   /**
140    * How many bytes does this signature sign?
141    * (including this purpose header); in network
142    * byte order (!).
143    */
144   uint32_t size GNUNET_PACKED;
145
146   /**
147    * What does this signature vouch for?  This
148    * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
149    * constant (from gnunet_signatures.h).  In
150    * network byte order!
151    */
152   uint32_t purpose GNUNET_PACKED;
153
154 };
155
156
157 /**
158  * @brief an ECC signature using EdDSA.
159  * See https://gnunet.org/ed25519
160  */
161 struct GNUNET_CRYPTO_EddsaSignature
162 {
163
164   /**
165    * R value.
166    */
167   unsigned char r[256 / 8];
168
169   /**
170    * S value.
171    */
172   unsigned char s[256 / 8];
173
174 };
175
176
177
178 /**
179  * @brief an ECC signature using ECDSA
180  */
181 struct GNUNET_CRYPTO_EcdsaSignature
182 {
183
184   /**
185    * R value.
186    */
187   unsigned char r[256 / 8];
188
189   /**
190    * S value.
191    */
192   unsigned char s[256 / 8];
193
194 };
195
196
197 /**
198  * Public ECC key (always for Curve25519) encoded in a format suitable
199  * for network transmission and EdDSA signatures.
200  */
201 struct GNUNET_CRYPTO_EddsaPublicKey
202 {
203   /**
204    * Q consists of an x- and a y-value, each mod p (256 bits), given
205    * here in affine coordinates and Ed25519 standard compact format.
206    */
207   unsigned char q_y[256 / 8];
208
209 };
210
211
212 /**
213  * Public ECC key (always for Curve25519) encoded in a format suitable
214  * for network transmission and ECDSA signatures.
215  */
216 struct GNUNET_CRYPTO_EcdsaPublicKey
217 {
218   /**
219    * Q consists of an x- and a y-value, each mod p (256 bits), given
220    * here in affine coordinates and Ed25519 standard compact format.
221    */
222   unsigned char q_y[256 / 8];
223
224 };
225
226
227 /**
228  * The identity of the host (wraps the signing key of the peer).
229  */
230 struct GNUNET_PeerIdentity
231 {
232   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
233 };
234
235
236 /**
237  * Public ECC key (always for Curve25519) encoded in a format suitable
238  * for network transmission and encryption (ECDH),
239  * See http://cr.yp.to/ecdh.html
240  */
241 struct GNUNET_CRYPTO_EcdhePublicKey
242 {
243   /**
244    * Q consists of an x- and a y-value, each mod p (256 bits), given
245    * here in affine coordinates and Ed25519 standard compact format.
246    */
247   unsigned char q_y[256 / 8];
248 };
249
250
251 /**
252  * Private ECC key encoded for transmission.  To be used only for ECDH
253  * key exchange (ECDHE to be precise).
254  */
255 struct GNUNET_CRYPTO_EcdhePrivateKey
256 {
257   /**
258    * d is a value mod n, where n has at most 256 bits.
259    */
260   unsigned char d[256 / 8];
261
262 };
263
264 /**
265  * Private ECC key encoded for transmission.  To be used only for ECDSA
266  * signatures.
267  */
268 struct GNUNET_CRYPTO_EcdsaPrivateKey
269 {
270   /**
271    * d is a value mod n, where n has at most 256 bits.
272    */
273   unsigned char d[256 / 8];
274
275 };
276
277 /**
278  * Private ECC key encoded for transmission.  To be used only for EdDSA
279  * signatures.
280  */
281 struct GNUNET_CRYPTO_EddsaPrivateKey
282 {
283   /**
284    * d is a value mod n, where n has at most 256 bits.
285    */
286   unsigned char d[256 / 8];
287
288 };
289
290
291 /**
292  * @brief type for session keys
293  */
294 struct GNUNET_CRYPTO_SymmetricSessionKey
295 {
296   /**
297    * Actual key for AES.
298    */
299   unsigned char aes_key[GNUNET_CRYPTO_AES_KEY_LENGTH];
300
301   /**
302    * Actual key for TwoFish.
303    */
304   unsigned char twofish_key[GNUNET_CRYPTO_AES_KEY_LENGTH];
305
306 };
307
308 GNUNET_NETWORK_STRUCT_END
309
310 /**
311  * @brief IV for sym cipher
312  *
313  * NOTE: must be smaller (!) in size than the
314  * `struct GNUNET_HashCode`.
315  */
316 struct GNUNET_CRYPTO_SymmetricInitializationVector
317 {
318   unsigned char aes_iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
319
320   unsigned char twofish_iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
321 };
322
323
324 /**
325  * @brief type for (message) authentication keys
326  */
327 struct GNUNET_CRYPTO_AuthKey
328 {
329   unsigned char key[GNUNET_CRYPTO_HASH_LENGTH];
330 };
331
332
333 /**
334  * Size of paillier plain texts and public keys.
335  * Private keys and ciphertexts are twice this size.
336  */
337 #define GNUNET_CRYPTO_PAILLIER_BITS 2048
338
339
340 /**
341  * Paillier public key.
342  */
343 struct GNUNET_CRYPTO_PaillierPublicKey
344 {
345   /**
346    * N value.
347    */
348   unsigned char n[GNUNET_CRYPTO_PAILLIER_BITS / 8];
349 };
350
351
352 /**
353  * Paillier public key.
354  */
355 struct GNUNET_CRYPTO_PaillierPrivateKey
356 {
357   /**
358    * Lambda-component of the private key.
359    */
360   unsigned char lambda[GNUNET_CRYPTO_PAILLIER_BITS / 8];
361   /**
362    * Mu-component of the private key.
363    */
364   unsigned char mu[GNUNET_CRYPTO_PAILLIER_BITS / 8];
365 };
366
367
368 /**
369  * Paillier plaintext.
370  */
371 struct GNUNET_CRYPTO_PaillierPlaintext
372 {
373   /**
374    * The bits of the plaintext.
375    */
376   unsigned char bits[GNUNET_CRYPTO_PAILLIER_BITS / 8];
377 };
378
379
380 /**
381  * Paillier ciphertext.
382  */
383 struct GNUNET_CRYPTO_PaillierCiphertext
384 {
385   /**
386    * The bits of the ciphertext.
387    */
388   unsigned char bits[GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8];
389 };
390
391
392 /* **************** Functions and Macros ************* */
393
394 /**
395  * @ingroup crypto
396  * Seed a weak random generator. Only #GNUNET_CRYPTO_QUALITY_WEAK-mode generator
397  * can be seeded.
398  *
399  * @param seed the seed to use
400  */
401 void
402 GNUNET_CRYPTO_seed_weak_random (int32_t seed);
403
404
405 /**
406  * Perform an incremental step in a CRC16 (for TCP/IP) calculation.
407  *
408  * @param sum current sum, initially 0
409  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
410  * @param len number of bytes in @a buf, must be multiple of 2
411  * @return updated crc sum (must be subjected to #GNUNET_CRYPTO_crc16_finish to get actual crc16)
412  */
413 uint32_t
414 GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len);
415
416
417 /**
418  * Convert results from GNUNET_CRYPTO_crc16_step to final crc16.
419  *
420  * @param sum cummulative sum
421  * @return crc16 value
422  */
423 uint16_t
424 GNUNET_CRYPTO_crc16_finish (uint32_t sum);
425
426
427 /**
428  * @ingroup hash
429  * Calculate the checksum of a buffer in one step.
430  *
431  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
432  * @param len number of bytes in @a buf, must be multiple of 2
433  * @return crc16 value
434  */
435 uint16_t
436 GNUNET_CRYPTO_crc16_n (const void *buf, size_t len);
437
438
439 /**
440  * @ingroup hash
441  * Compute the CRC32 checksum for the first len
442  * bytes of the buffer.
443  *
444  * @param buf the data over which we're taking the CRC
445  * @param len the length of the buffer @a buf in bytes
446  * @return the resulting CRC32 checksum
447  */
448 int32_t
449 GNUNET_CRYPTO_crc32_n (const void *buf, size_t len);
450
451
452 /**
453  * @ingroup crypto
454  * Fill block with a random values.
455  *
456  * @param mode desired quality of the random number
457  * @param buffer the buffer to fill
458  * @param length buffer length
459  */
460 void
461 GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, void *buffer, size_t length);
462
463 /**
464  * @ingroup crypto
465  * Produce a random value.
466  *
467  * @param mode desired quality of the random number
468  * @param i the upper limit (exclusive) for the random number
469  * @return a random value in the interval [0,@a i) (exclusive).
470  */
471 uint32_t
472 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i);
473
474
475 /**
476  * @ingroup crypto
477  * Random on unsigned 64-bit values.
478  *
479  * @param mode desired quality of the random number
480  * @param max value returned will be in range [0,@a max) (exclusive)
481  * @return random 64-bit number
482  */
483 uint64_t
484 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max);
485
486
487 /**
488  * @ingroup crypto
489  * Get an array with a random permutation of the
490  * numbers 0...n-1.
491  * @param mode #GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used,
492  *             #GNUNET_CRYPTO_QUALITY_WEAK or #GNUNET_CRYPTO_QUALITY_NONCE otherwise
493  * @param n the size of the array
494  * @return the permutation array (allocated from heap)
495  */
496 unsigned int *
497 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n);
498
499
500 /**
501  * @ingroup crypto
502  * Create a new random session key.
503  *
504  * @param key key to initialize
505  */
506 void
507 GNUNET_CRYPTO_symmetric_create_session_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key);
508
509
510 /**
511  * @ingroup crypto
512  * Encrypt a block using a symmetric sessionkey.
513  *
514  * @param block the block to encrypt
515  * @param size the size of the @a block
516  * @param sessionkey the key used to encrypt
517  * @param iv the initialization vector to use, use INITVALUE
518  *        for streams.
519  * @return the size of the encrypted block, -1 for errors
520  */
521 ssize_t
522 GNUNET_CRYPTO_symmetric_encrypt (const void *block, size_t size,
523                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
524                                  const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
525                                  void *result);
526
527
528 /**
529  * @ingroup crypto
530  * Decrypt a given block using a symmetric sessionkey.
531  *
532  * @param block the data to decrypt, encoded as returned by encrypt
533  * @param size how big is the block?
534  * @param sessionkey the key used to decrypt
535  * @param iv the initialization vector to use
536  * @param result address to store the result at
537  * @return -1 on failure, size of decrypted block on success
538  */
539 ssize_t
540 GNUNET_CRYPTO_symmetric_decrypt (const void *block, size_t size,
541                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
542                                  const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
543                                  void *result);
544
545
546 /**
547  * @ingroup crypto
548  * @brief Derive an IV
549  * @param iv initialization vector
550  * @param skey session key
551  * @param salt salt for the derivation
552  * @param salt_len size of the @a salt
553  * @param ... pairs of void * & size_t for context chunks, terminated by NULL
554  */
555 void
556 GNUNET_CRYPTO_symmetric_derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
557                                    const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
558                                    const void *salt,
559                                    size_t salt_len, ...);
560
561
562 /**
563  * @brief Derive an IV
564  * @param iv initialization vector
565  * @param skey session key
566  * @param salt salt for the derivation
567  * @param salt_len size of the @a salt
568  * @param argp pairs of void * & size_t for context chunks, terminated by NULL
569  */
570 void
571 GNUNET_CRYPTO_symmetric_derive_iv_v (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
572                                      const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
573                                      const void *salt,
574                                      size_t salt_len,
575                                      va_list argp);
576
577
578 /**
579  * @ingroup hash
580  * Convert hash to ASCII encoding.
581  * @param block the hash code
582  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
583  *  safely cast to char*, a '\\0' termination is set).
584  */
585 void
586 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode * block,
587                            struct GNUNET_CRYPTO_HashAsciiEncoded *result);
588
589
590 /**
591  * @ingroup hash
592  * Convert ASCII encoding back to a 'struct GNUNET_HashCode'
593  *
594  * @param enc the encoding
595  * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
596  * @param result where to store the hash code
597  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
598  */
599 int
600 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
601                                  struct GNUNET_HashCode *result);
602
603
604 /**
605  * @ingroup hash
606  * Convert ASCII encoding back to `struct GNUNET_HashCode`
607  *
608  * @param enc the encoding
609  * @param result where to store the hash code
610  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
611  */
612 #define GNUNET_CRYPTO_hash_from_string(enc, result) \
613   GNUNET_CRYPTO_hash_from_string2 (enc, strlen(enc), result)
614
615
616 /**
617  * @ingroup hash
618  *
619  * Compute the distance between 2 hashcodes.  The
620  * computation must be fast, not involve @a a[0] or @a a[4] (they're used
621  * elsewhere), and be somewhat consistent. And of course, the result
622  * should be a positive number.
623  *
624  * @param a some hash code
625  * @param b some hash code
626  * @return number between 0 and UINT32_MAX
627  */
628 uint32_t
629 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
630                                  const struct GNUNET_HashCode *b);
631
632
633 /**
634  * @ingroup hash
635  * Compute hash of a given block.
636  *
637  * @param block the data to hash
638  * @param size size of the @a block
639  * @param ret pointer to where to write the hashcode
640  */
641 void
642 GNUNET_CRYPTO_hash (const void *block, size_t size, struct GNUNET_HashCode * ret);
643
644
645 /**
646  * @ingroup hash
647  * Calculate HMAC of a message (RFC 2104)
648  *
649  * @param key secret key
650  * @param plaintext input plaintext
651  * @param plaintext_len length of @a plaintext
652  * @param hmac where to store the hmac
653  */
654 void
655 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
656                     const void *plaintext, size_t plaintext_len,
657                     struct GNUNET_HashCode * hmac);
658
659
660 /**
661  * Function called once the hash computation over the
662  * specified file has completed.
663  *
664  * @param cls closure
665  * @param res resulting hash, NULL on error
666  */
667 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
668                                                      const struct GNUNET_HashCode *res);
669
670
671 /**
672  * Handle to file hashing operation.
673  */
674 struct GNUNET_CRYPTO_FileHashContext;
675
676
677 /**
678  * @ingroup hash
679  * Compute the hash of an entire file.
680  *
681  * @param priority scheduling priority to use
682  * @param filename name of file to hash
683  * @param blocksize number of bytes to process in one task
684  * @param callback function to call upon completion
685  * @param callback_cls closure for @a callback
686  * @return NULL on (immediate) errror
687  */
688 struct GNUNET_CRYPTO_FileHashContext *
689 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
690                          const char *filename, size_t blocksize,
691                          GNUNET_CRYPTO_HashCompletedCallback callback,
692                          void *callback_cls);
693
694
695 /**
696  * Cancel a file hashing operation.
697  *
698  * @param fhc operation to cancel (callback must not yet have been invoked)
699  */
700 void
701 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
702
703
704 /**
705  * @ingroup hash
706  * Create a random hash code.
707  *
708  * @param mode desired quality level
709  * @param result hash code that is randomized
710  */
711 void
712 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
713                                   struct GNUNET_HashCode *result);
714
715
716 /**
717  * @ingroup hash
718  * compute @a result = @a b - @a a
719  *
720  * @param a some hash code
721  * @param b some hash code
722  * @param result set to @a b - @a a
723  */
724 void
725 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
726                                const struct GNUNET_HashCode *b,
727                                struct GNUNET_HashCode *result);
728
729
730 /**
731  * @ingroup hash
732  * compute @a result = @a a + @a delta
733  *
734  * @param a some hash code
735  * @param delta some hash code
736  * @param result set to @a a + @a delta
737  */
738 void
739 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a,
740                         const struct GNUNET_HashCode *delta,
741                         struct GNUNET_HashCode *result);
742
743
744 /**
745  * @ingroup hash
746  * compute result = a ^ b
747  *
748  * @param a some hash code
749  * @param b some hash code
750  * @param result set to @a a ^ @a b
751  */
752 void
753 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode * a, const struct GNUNET_HashCode * b,
754                         struct GNUNET_HashCode * result);
755
756
757 /**
758  * @ingroup hash
759  * Convert a hashcode into a key.
760  *
761  * @param hc hash code that serves to generate the key
762  * @param skey set to a valid session key
763  * @param iv set to a valid initialization vector
764  */
765 void
766 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
767                                struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
768                                struct GNUNET_CRYPTO_SymmetricInitializationVector *iv);
769
770
771 /**
772  * @ingroup hash
773  * Obtain a bit from a hashcode.
774  *
775  * @param code the `struct GNUNET_HashCode` to index bit-wise
776  * @param bit index into the hashcode, [0...159]
777  * @return Bit \a bit from hashcode \a code, -1 for invalid index
778  */
779 int
780 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code,
781                             unsigned int bit);
782
783
784 /**
785  * @ingroup hash
786  * Determine how many low order bits match in two
787  * `struct GNUNET_HashCodes`.  i.e. - 010011 and 011111 share
788  * the first two lowest order bits, and therefore the
789  * return value is two (NOT XOR distance, nor how many
790  * bits match absolutely!).
791  *
792  * @param first the first hashcode
793  * @param second the hashcode to compare first to
794  * @return the number of bits that match
795  */
796 unsigned int
797 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
798                                   const struct GNUNET_HashCode *second);
799
800
801 /**
802  * @ingroup hash
803  * Compare function for HashCodes, producing a total ordering
804  * of all hashcodes.
805  *
806  * @param h1 some hash code
807  * @param h2 some hash code
808  * @return 1 if @a h1 > @a h2, -1 if @a h1 < @a h2 and 0 if @a h1 == @a h2.
809  */
810 int
811 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
812                         const struct GNUNET_HashCode *h2);
813
814
815 /**
816  * @ingroup hash
817  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
818  * in the XOR metric (Kademlia).
819  *
820  * @param h1 some hash code
821  * @param h2 some hash code
822  * @param target some hash code
823  * @return -1 if @a h1 is closer, 1 if @a h2 is closer and 0 if @a h1== @a h2.
824  */
825 int
826 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
827                            const struct GNUNET_HashCode *h2,
828                            const struct GNUNET_HashCode *target);
829
830
831 /**
832  * @ingroup hash
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_SymmetricSessionKey *rkey,
843                                  const void *salt, size_t salt_len,
844                                  va_list argp);
845
846
847 /**
848  * @ingroup hash
849  * @brief Derive an authentication key
850  * @param key authentication key
851  * @param rkey root key
852  * @param salt salt
853  * @param salt_len size of the salt
854  * @param ... pair of void * & size_t for context chunks, terminated by NULL
855  */
856 void
857 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
858                                const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
859                                const void *salt, size_t salt_len, ...);
860
861
862 /**
863  * @ingroup hash
864  * @brief Derive key
865  * @param result buffer for the derived key, allocated by caller
866  * @param out_len desired length of the derived key
867  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
868  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
869  * @param xts salt
870  * @param xts_len length of @a xts
871  * @param skm source key material
872  * @param skm_len length of @a skm
873  * @param ... pair of void * & size_t for context chunks, terminated by NULL
874  * @return #GNUNET_YES on success
875  */
876 int
877 GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo, int prf_algo,
878                     const void *xts, size_t xts_len, const void *skm,
879                     size_t skm_len, ...);
880
881
882 /**
883  * @ingroup hash
884  * @brief Derive key
885  * @param result buffer for the derived key, allocated by caller
886  * @param out_len desired length of the derived key
887  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
888  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
889  * @param xts salt
890  * @param xts_len length of @a xts
891  * @param skm source key material
892  * @param skm_len length of @a skm
893  * @param argp va_list of void * & size_t pairs for context chunks
894  * @return #GNUNET_YES on success
895  */
896 int
897 GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
898                       const void *xts, size_t xts_len, const void *skm,
899                       size_t skm_len, va_list argp);
900
901
902 /**
903  * @brief Derive key
904  * @param result buffer for the derived key, allocated by caller
905  * @param out_len desired length of the derived key
906  * @param xts salt
907  * @param xts_len length of @a xts
908  * @param skm source key material
909  * @param skm_len length of @a skm
910  * @param argp va_list of void * & size_t pairs for context chunks
911  * @return #GNUNET_YES on success
912  */
913 int
914 GNUNET_CRYPTO_kdf_v (void *result, size_t out_len, const void *xts,
915                      size_t xts_len, const void *skm, size_t skm_len,
916                      va_list argp);
917
918
919 /**
920  * @ingroup hash
921  * @brief Derive key
922  * @param result buffer for the derived key, allocated by caller
923  * @param out_len desired length of the derived key
924  * @param xts salt
925  * @param xts_len length of @a xts
926  * @param skm source key material
927  * @param skm_len length of @a skm
928  * @param ... void * & size_t pairs for context chunks
929  * @return #GNUNET_YES on success
930  */
931 int
932 GNUNET_CRYPTO_kdf (void *result, size_t out_len, const void *xts,
933                    size_t xts_len, const void *skm, size_t skm_len, ...);
934
935
936 /**
937  * @ingroup crypto
938  * Extract the public key for the given private key.
939  *
940  * @param priv the private key
941  * @param pub where to write the public key
942  */
943 void
944 GNUNET_CRYPTO_ecdsa_key_get_public (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
945                                     struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
946
947 /**
948  * @ingroup crypto
949  * Extract the public key for the given private key.
950  *
951  * @param priv the private key
952  * @param pub where to write the public key
953  */
954 void
955 GNUNET_CRYPTO_eddsa_key_get_public (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
956                                     struct GNUNET_CRYPTO_EddsaPublicKey *pub);
957
958
959 /**
960  * @ingroup crypto
961  * Extract the public key for the given private key.
962  *
963  * @param priv the private key
964  * @param pub where to write the public key
965  */
966 void
967 GNUNET_CRYPTO_ecdhe_key_get_public (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
968                                     struct GNUNET_CRYPTO_EcdhePublicKey *pub);
969
970
971 /**
972  * Convert a public key to a string.
973  *
974  * @param pub key to convert
975  * @return string representing @a pub
976  */
977 char *
978 GNUNET_CRYPTO_ecdsa_public_key_to_string (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
979
980
981 /**
982  * Convert a public key to a string.
983  *
984  * @param pub key to convert
985  * @return string representing @a pub
986  */
987 char *
988 GNUNET_CRYPTO_eddsa_public_key_to_string (const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
989
990
991 /**
992  * Convert a string representing a public key to a public key.
993  *
994  * @param enc encoded public key
995  * @param enclen number of bytes in @a enc (without 0-terminator)
996  * @param pub where to store the public key
997  * @return #GNUNET_OK on success
998  */
999 int
1000 GNUNET_CRYPTO_ecdsa_public_key_from_string (const char *enc,
1001                                             size_t enclen,
1002                                             struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1003
1004
1005 /**
1006  * Convert a string representing a public key to a public key.
1007  *
1008  * @param enc encoded public key
1009  * @param enclen number of bytes in @a enc (without 0-terminator)
1010  * @param pub where to store the public key
1011  * @return #GNUNET_OK on success
1012  */
1013 int
1014 GNUNET_CRYPTO_eddsa_public_key_from_string (const char *enc,
1015                                             size_t enclen,
1016                                             struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1017
1018
1019 /**
1020  * @ingroup crypto
1021  * Create a new private key by reading it from a file.  If the
1022  * files does not exist, create a new key and write it to the
1023  * file.  Caller must free return value.  Note that this function
1024  * can not guarantee that another process might not be trying
1025  * the same operation on the same file at the same time.
1026  * If the contents of the file
1027  * are invalid the old file is deleted and a fresh key is
1028  * created.
1029  *
1030  * @param filename name of file to use to store the key
1031  * @return new private key, NULL on error (for example,
1032  *   permission denied); free using #GNUNET_free
1033  */
1034 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1035 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename);
1036
1037
1038 /**
1039  * @ingroup crypto
1040  * Create a new private key by reading it from a file.  If the
1041  * files does not exist, create a new key and write it to the
1042  * file.  Caller must free return value.  Note that this function
1043  * can not guarantee that another process might not be trying
1044  * the same operation on the same file at the same time.
1045  * If the contents of the file
1046  * are invalid the old file is deleted and a fresh key is
1047  * created.
1048  *
1049  * @param filename name of file to use to store the key
1050  * @return new private key, NULL on error (for example,
1051  *   permission denied); free using #GNUNET_free
1052  */
1053 struct GNUNET_CRYPTO_EddsaPrivateKey *
1054 GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename);
1055
1056
1057 /**
1058  * @ingroup crypto
1059  * Create a new private key by reading our peer's key from
1060  * the file specified in the configuration.
1061  *
1062  * @param cfg the configuration to use
1063  * @return new private key, NULL on error (for example,
1064  *   permission denied); free using #GNUNET_free
1065  */
1066 struct GNUNET_CRYPTO_EddsaPrivateKey *
1067 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg);
1068
1069
1070 /**
1071  * @ingroup crypto
1072  * Create a new private key. Caller must free return value.
1073  *
1074  * @return fresh private key; free using #GNUNET_free
1075  */
1076 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1077 GNUNET_CRYPTO_ecdsa_key_create (void);
1078
1079
1080 /**
1081  * @ingroup crypto
1082  * Create a new private key. Caller must free return value.
1083  *
1084  * @return fresh private key; free using #GNUNET_free
1085  */
1086 struct GNUNET_CRYPTO_EddsaPrivateKey *
1087 GNUNET_CRYPTO_eddsa_key_create (void);
1088
1089
1090 /**
1091  * @ingroup crypto
1092  * Create a new private key. Caller must free return value.
1093  *
1094  * @return fresh private key; free using #GNUNET_free
1095  */
1096 struct GNUNET_CRYPTO_EcdhePrivateKey *
1097 GNUNET_CRYPTO_ecdhe_key_create (void);
1098
1099
1100 /**
1101  * @ingroup crypto
1102  * Clear memory that was used to store a private key.
1103  *
1104  * @param pk location of the key
1105  */
1106 void
1107 GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk);
1108
1109
1110 /**
1111  * @ingroup crypto
1112  * Clear memory that was used to store a private key.
1113  *
1114  * @param pk location of the key
1115  */
1116 void
1117 GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk);
1118
1119 /**
1120  * @ingroup crypto
1121  * Clear memory that was used to store a private key.
1122  *
1123  * @param pk location of the key
1124  */
1125 void
1126 GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk);
1127
1128
1129 /**
1130  * @ingroup crypto
1131  * Get the shared private key we use for anonymous users.
1132  *
1133  * @return "anonymous" private key; do not free
1134  */
1135 const struct GNUNET_CRYPTO_EcdsaPrivateKey *
1136 GNUNET_CRYPTO_ecdsa_key_get_anonymous (void);
1137
1138
1139 /**
1140  * @ingroup crypto
1141  * Setup a hostkey file for a peer given the name of the
1142  * configuration file (!).  This function is used so that
1143  * at a later point code can be certain that reading a
1144  * hostkey is fast (for example in time-dependent testcases).
1145 *
1146  * @param cfg_name name of the configuration file to use
1147  */
1148 void
1149 GNUNET_CRYPTO_eddsa_setup_hostkey (const char *cfg_name);
1150
1151
1152 /**
1153  * @ingroup crypto
1154  * Retrieve the identity of the host's peer.
1155  *
1156  * @param cfg configuration to use
1157  * @param dst pointer to where to write the peer identity
1158  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
1159  *         could not be retrieved
1160  */
1161 int
1162 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
1163                                  struct GNUNET_PeerIdentity *dst);
1164
1165 /**
1166  * Compare two Peer Identities.
1167  *
1168  * @param first first peer identity
1169  * @param second second peer identity
1170  * @return bigger than 0 if first > second,
1171  *         0 if they are the same
1172  *         smaller than 0 if second > first
1173  */
1174 int
1175 GNUNET_CRYPTO_cmp_peer_identity (const struct GNUNET_PeerIdentity *first,
1176                                  const struct GNUNET_PeerIdentity *second);
1177
1178
1179 /**
1180  * @ingroup crypto
1181  * Derive key material from a public and a private ECC key.
1182  *
1183  * @param priv private key to use for the ECDH (x)
1184  * @param pub public key to use for the ECDH (yG)
1185  * @param key_material where to write the key material (xyG)
1186  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1187  */
1188 int
1189 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1190                         const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1191                         struct GNUNET_HashCode *key_material);
1192
1193
1194 /**
1195  * @ingroup crypto
1196  * EdDSA sign a given block.
1197  *
1198  * @param priv private key to use for the signing
1199  * @param purpose what to sign (size, purpose)
1200  * @param sig where to write the signature
1201  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1202  */
1203 int
1204 GNUNET_CRYPTO_eddsa_sign (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1205                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1206                           struct GNUNET_CRYPTO_EddsaSignature *sig);
1207
1208
1209 /**
1210  * @ingroup crypto
1211  * ECDSA Sign a given block.
1212  *
1213  * @param priv private key to use for the signing
1214  * @param purpose what to sign (size, purpose)
1215  * @param sig where to write the signature
1216  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1217  */
1218 int
1219 GNUNET_CRYPTO_ecdsa_sign (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1220                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1221                           struct GNUNET_CRYPTO_EcdsaSignature *sig);
1222
1223 /**
1224  * @ingroup crypto
1225  * Verify EdDSA signature.
1226  *
1227  * @param purpose what is the purpose that the signature should have?
1228  * @param validate block to validate (size, purpose, data)
1229  * @param sig signature that is being validated
1230  * @param pub public key of the signer
1231  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1232  */
1233 int
1234 GNUNET_CRYPTO_eddsa_verify (uint32_t purpose,
1235                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1236                             const struct GNUNET_CRYPTO_EddsaSignature *sig,
1237                             const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1238
1239
1240
1241 /**
1242  * @ingroup crypto
1243  * Verify ECDSA signature.
1244  *
1245  * @param purpose what is the purpose that the signature should have?
1246  * @param validate block to validate (size, purpose, data)
1247  * @param sig signature that is being validated
1248  * @param pub public key of the signer
1249  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1250  */
1251 int
1252 GNUNET_CRYPTO_ecdsa_verify (uint32_t purpose,
1253                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1254                             const struct GNUNET_CRYPTO_EcdsaSignature *sig,
1255                             const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1256
1257
1258 /**
1259  * @ingroup crypto
1260  * Derive a private key from a given private key and a label.
1261  * Essentially calculates a private key 'h = H(l,P) * d mod n'
1262  * where n is the size of the ECC group and P is the public
1263  * key associated with the private key 'd'.
1264  *
1265  * @param priv original private key
1266  * @param label label to use for key deriviation
1267  * @param context additional context to use for HKDF of 'h';
1268  *        typically the name of the subsystem/application
1269  * @return derived private key
1270  */
1271 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1272 GNUNET_CRYPTO_ecdsa_private_key_derive (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1273                                         const char *label,
1274                                         const char *context);
1275
1276
1277 /**
1278  * @ingroup crypto
1279  * Derive a public key from a given public key and a label.
1280  * Essentially calculates a public key 'V = H(l,P) * P'.
1281  *
1282  * @param pub original public key
1283  * @param label label to use for key deriviation
1284  * @param context additional context to use for HKDF of 'h'.
1285  *        typically the name of the subsystem/application
1286  * @param result where to write the derived public key
1287  */
1288 void
1289 GNUNET_CRYPTO_ecdsa_public_key_derive (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1290                                        const char *label,
1291                                        const char *context,
1292                                        struct GNUNET_CRYPTO_EcdsaPublicKey *result);
1293
1294
1295 /**
1296  * Output the given MPI value to the given buffer in network
1297  * byte order.  The MPI @a val may not be negative.
1298  *
1299  * @param buf where to output to
1300  * @param size number of bytes in @a buf
1301  * @param val value to write to @a buf
1302  */
1303 void
1304 GNUNET_CRYPTO_mpi_print_unsigned (void *buf,
1305                                   size_t size,
1306                                   gcry_mpi_t val);
1307
1308
1309 /**
1310  * Convert data buffer into MPI value.
1311  * The buffer is interpreted as network
1312  * byte order, unsigned integer.
1313  *
1314  * @param result where to store MPI value (allocated)
1315  * @param data raw data (GCRYMPI_FMT_USG)
1316  * @param size number of bytes in @a data
1317  */
1318 void
1319 GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result,
1320                                  const void *data,
1321                                  size_t size);
1322
1323
1324 /**
1325  * Create a freshly generated paillier public key.
1326  *
1327  * @param[out] public_key Where to store the public key?
1328  * @param[out] private_key Where to store the private key?
1329  */
1330 void
1331 GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1332                                struct GNUNET_CRYPTO_PaillierPrivateKey *private_key);
1333
1334
1335 /**
1336  * Encrypt a plaintext with a paillier public key.
1337  *
1338  * @param public_key Public key to use.
1339  * @param plaintext Plaintext to encrypt.
1340  * @param[out] ciphertext Encrytion of @a plaintext with @a public_key.
1341  */
1342 void
1343 GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1344                                 const struct GNUNET_CRYPTO_PaillierPlaintext *plaintext,
1345                                 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext);
1346
1347
1348 /**
1349  * Decrypt a paillier ciphertext with a private key.
1350  *
1351  * @param private_key Private key to use for decryption.
1352  * @param public_key Public key to use for decryption.
1353  * @param ciphertext Ciphertext to decrypt.
1354  * @param[out] plaintext Decryption of @a ciphertext with @private_key.
1355  */
1356 void
1357 GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key,
1358                                 const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1359                                 const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext,
1360                                 struct GNUNET_CRYPTO_PaillierPlaintext *plaintext);
1361
1362
1363 /**
1364  * Compute a ciphertext that represents the sum of the plaintext in @a x1 and @a x2
1365  *
1366  * Note that this operation can only be done a finite number of times
1367  * before an overflow occurs.
1368  *
1369  * @param x1 Paillier cipher text.
1370  * @param x2 Paillier cipher text.
1371  * @param[out] result Result of the homomorphic operation.
1372  * @return #GNUNET_OK if the result could be computed,
1373  *         #GNUNET_SYSERR if no more homomorphic operations are remaining.
1374  */
1375 int
1376 GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierCiphertext *x1,
1377                                 const struct GNUNET_CRYPTO_PaillierCiphertext *x2,
1378                                 const struct GNUNET_CRYPTO_PaillierCiphertext *result);
1379
1380
1381 #if 0                           /* keep Emacsens' auto-indent happy */
1382 {
1383 #endif
1384 #ifdef __cplusplus
1385 }
1386 #endif
1387
1388
1389 /* ifndef GNUNET_CRYPTO_LIB_H */
1390 #endif
1391 /* end of gnunet_crypto_lib.h */