- header sync
[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    * guaranteed minimum number of homomorphic operations with this ciphertext
387    */
388   uint32_t remaining_ops GNUNET_PACKED;
389   
390   /**
391    * The bits of the ciphertext.
392    */
393   unsigned char bits[GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8];
394 };
395
396
397 /* **************** Functions and Macros ************* */
398
399 /**
400  * @ingroup crypto
401  * Seed a weak random generator. Only #GNUNET_CRYPTO_QUALITY_WEAK-mode generator
402  * can be seeded.
403  *
404  * @param seed the seed to use
405  */
406 void
407 GNUNET_CRYPTO_seed_weak_random (int32_t seed);
408
409
410 /**
411  * Perform an incremental step in a CRC16 (for TCP/IP) calculation.
412  *
413  * @param sum current sum, initially 0
414  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
415  * @param len number of bytes in @a buf, must be multiple of 2
416  * @return updated crc sum (must be subjected to #GNUNET_CRYPTO_crc16_finish to get actual crc16)
417  */
418 uint32_t
419 GNUNET_CRYPTO_crc16_step (uint32_t sum, const void *buf, size_t len);
420
421
422 /**
423  * Convert results from GNUNET_CRYPTO_crc16_step to final crc16.
424  *
425  * @param sum cummulative sum
426  * @return crc16 value
427  */
428 uint16_t
429 GNUNET_CRYPTO_crc16_finish (uint32_t sum);
430
431
432 /**
433  * @ingroup hash
434  * Calculate the checksum of a buffer in one step.
435  *
436  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
437  * @param len number of bytes in @a buf, must be multiple of 2
438  * @return crc16 value
439  */
440 uint16_t
441 GNUNET_CRYPTO_crc16_n (const void *buf, size_t len);
442
443
444 /**
445  * @ingroup hash
446  * Compute the CRC32 checksum for the first len
447  * bytes of the buffer.
448  *
449  * @param buf the data over which we're taking the CRC
450  * @param len the length of the buffer @a buf in bytes
451  * @return the resulting CRC32 checksum
452  */
453 int32_t
454 GNUNET_CRYPTO_crc32_n (const void *buf, size_t len);
455
456
457 /**
458  * @ingroup crypto
459  * Fill block with a random values.
460  *
461  * @param mode desired quality of the random number
462  * @param buffer the buffer to fill
463  * @param length buffer length
464  */
465 void
466 GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode, void *buffer, size_t length);
467
468 /**
469  * @ingroup crypto
470  * Produce a random value.
471  *
472  * @param mode desired quality of the random number
473  * @param i the upper limit (exclusive) for the random number
474  * @return a random value in the interval [0,@a i) (exclusive).
475  */
476 uint32_t
477 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i);
478
479
480 /**
481  * @ingroup crypto
482  * Random on unsigned 64-bit values.
483  *
484  * @param mode desired quality of the random number
485  * @param max value returned will be in range [0,@a max) (exclusive)
486  * @return random 64-bit number
487  */
488 uint64_t
489 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode, uint64_t max);
490
491
492 /**
493  * @ingroup crypto
494  * Get an array with a random permutation of the
495  * numbers 0...n-1.
496  * @param mode #GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used,
497  *             #GNUNET_CRYPTO_QUALITY_WEAK or #GNUNET_CRYPTO_QUALITY_NONCE otherwise
498  * @param n the size of the array
499  * @return the permutation array (allocated from heap)
500  */
501 unsigned int *
502 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode, unsigned int n);
503
504
505 /**
506  * @ingroup crypto
507  * Create a new random session key.
508  *
509  * @param key key to initialize
510  */
511 void
512 GNUNET_CRYPTO_symmetric_create_session_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key);
513
514
515 /**
516  * @ingroup crypto
517  * Encrypt a block using a symmetric sessionkey.
518  *
519  * @param block the block to encrypt
520  * @param size the size of the @a block
521  * @param sessionkey the key used to encrypt
522  * @param iv the initialization vector to use, use INITVALUE
523  *        for streams.
524  * @return the size of the encrypted block, -1 for errors
525  */
526 ssize_t
527 GNUNET_CRYPTO_symmetric_encrypt (const void *block, size_t size,
528                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
529                                  const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
530                                  void *result);
531
532
533 /**
534  * @ingroup crypto
535  * Decrypt a given block using a symmetric sessionkey.
536  *
537  * @param block the data to decrypt, encoded as returned by encrypt
538  * @param size how big is the block?
539  * @param sessionkey the key used to decrypt
540  * @param iv the initialization vector to use
541  * @param result address to store the result at
542  * @return -1 on failure, size of decrypted block on success
543  */
544 ssize_t
545 GNUNET_CRYPTO_symmetric_decrypt (const void *block, size_t size,
546                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
547                                  const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
548                                  void *result);
549
550
551 /**
552  * @ingroup crypto
553  * @brief Derive an IV
554  * @param iv initialization vector
555  * @param skey session key
556  * @param salt salt for the derivation
557  * @param salt_len size of the @a salt
558  * @param ... pairs of void * & size_t for context chunks, terminated by NULL
559  */
560 void
561 GNUNET_CRYPTO_symmetric_derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
562                                    const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
563                                    const void *salt,
564                                    size_t salt_len, ...);
565
566
567 /**
568  * @brief Derive an IV
569  * @param iv initialization vector
570  * @param skey session key
571  * @param salt salt for the derivation
572  * @param salt_len size of the @a salt
573  * @param argp pairs of void * & size_t for context chunks, terminated by NULL
574  */
575 void
576 GNUNET_CRYPTO_symmetric_derive_iv_v (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
577                                      const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
578                                      const void *salt,
579                                      size_t salt_len,
580                                      va_list argp);
581
582
583 /**
584  * @ingroup hash
585  * Convert hash to ASCII encoding.
586  * @param block the hash code
587  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
588  *  safely cast to char*, a '\\0' termination is set).
589  */
590 void
591 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode * block,
592                            struct GNUNET_CRYPTO_HashAsciiEncoded *result);
593
594
595 /**
596  * @ingroup hash
597  * Convert ASCII encoding back to a 'struct GNUNET_HashCode'
598  *
599  * @param enc the encoding
600  * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
601  * @param result where to store the hash code
602  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
603  */
604 int
605 GNUNET_CRYPTO_hash_from_string2 (const char *enc, size_t enclen,
606                                  struct GNUNET_HashCode *result);
607
608
609 /**
610  * @ingroup hash
611  * Convert ASCII encoding back to `struct GNUNET_HashCode`
612  *
613  * @param enc the encoding
614  * @param result where to store the hash code
615  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
616  */
617 #define GNUNET_CRYPTO_hash_from_string(enc, result) \
618   GNUNET_CRYPTO_hash_from_string2 (enc, strlen(enc), result)
619
620
621 /**
622  * @ingroup hash
623  *
624  * Compute the distance between 2 hashcodes.  The
625  * computation must be fast, not involve @a a[0] or @a a[4] (they're used
626  * elsewhere), and be somewhat consistent. And of course, the result
627  * should be a positive number.
628  *
629  * @param a some hash code
630  * @param b some hash code
631  * @return number between 0 and UINT32_MAX
632  */
633 uint32_t
634 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
635                                  const struct GNUNET_HashCode *b);
636
637
638 /**
639  * @ingroup hash
640  * Compute hash of a given block.
641  *
642  * @param block the data to hash
643  * @param size size of the @a block
644  * @param ret pointer to where to write the hashcode
645  */
646 void
647 GNUNET_CRYPTO_hash (const void *block, size_t size, struct GNUNET_HashCode * ret);
648
649
650 /**
651  * @ingroup hash
652  * Calculate HMAC of a message (RFC 2104)
653  *
654  * @param key secret key
655  * @param plaintext input plaintext
656  * @param plaintext_len length of @a plaintext
657  * @param hmac where to store the hmac
658  */
659 void
660 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
661                     const void *plaintext, size_t plaintext_len,
662                     struct GNUNET_HashCode * hmac);
663
664
665 /**
666  * Function called once the hash computation over the
667  * specified file has completed.
668  *
669  * @param cls closure
670  * @param res resulting hash, NULL on error
671  */
672 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
673                                                      const struct GNUNET_HashCode *res);
674
675
676 /**
677  * Handle to file hashing operation.
678  */
679 struct GNUNET_CRYPTO_FileHashContext;
680
681
682 /**
683  * @ingroup hash
684  * Compute the hash of an entire file.
685  *
686  * @param priority scheduling priority to use
687  * @param filename name of file to hash
688  * @param blocksize number of bytes to process in one task
689  * @param callback function to call upon completion
690  * @param callback_cls closure for @a callback
691  * @return NULL on (immediate) errror
692  */
693 struct GNUNET_CRYPTO_FileHashContext *
694 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
695                          const char *filename, size_t blocksize,
696                          GNUNET_CRYPTO_HashCompletedCallback callback,
697                          void *callback_cls);
698
699
700 /**
701  * Cancel a file hashing operation.
702  *
703  * @param fhc operation to cancel (callback must not yet have been invoked)
704  */
705 void
706 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
707
708
709 /**
710  * @ingroup hash
711  * Create a random hash code.
712  *
713  * @param mode desired quality level
714  * @param result hash code that is randomized
715  */
716 void
717 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
718                                   struct GNUNET_HashCode *result);
719
720
721 /**
722  * @ingroup hash
723  * compute @a result = @a b - @a a
724  *
725  * @param a some hash code
726  * @param b some hash code
727  * @param result set to @a b - @a a
728  */
729 void
730 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
731                                const struct GNUNET_HashCode *b,
732                                struct GNUNET_HashCode *result);
733
734
735 /**
736  * @ingroup hash
737  * compute @a result = @a a + @a delta
738  *
739  * @param a some hash code
740  * @param delta some hash code
741  * @param result set to @a a + @a delta
742  */
743 void
744 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a,
745                         const struct GNUNET_HashCode *delta,
746                         struct GNUNET_HashCode *result);
747
748
749 /**
750  * @ingroup hash
751  * compute result = a ^ b
752  *
753  * @param a some hash code
754  * @param b some hash code
755  * @param result set to @a a ^ @a b
756  */
757 void
758 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode * a, const struct GNUNET_HashCode * b,
759                         struct GNUNET_HashCode * result);
760
761
762 /**
763  * @ingroup hash
764  * Convert a hashcode into a key.
765  *
766  * @param hc hash code that serves to generate the key
767  * @param skey set to a valid session key
768  * @param iv set to a valid initialization vector
769  */
770 void
771 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
772                                struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
773                                struct GNUNET_CRYPTO_SymmetricInitializationVector *iv);
774
775
776 /**
777  * @ingroup hash
778  * Obtain a bit from a hashcode.
779  *
780  * @param code the `struct GNUNET_HashCode` to index bit-wise
781  * @param bit index into the hashcode, [0...159]
782  * @return Bit \a bit from hashcode \a code, -1 for invalid index
783  */
784 int
785 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code,
786                             unsigned int bit);
787
788
789 /**
790  * @ingroup hash
791  * Determine how many low order bits match in two
792  * `struct GNUNET_HashCodes`.  i.e. - 010011 and 011111 share
793  * the first two lowest order bits, and therefore the
794  * return value is two (NOT XOR distance, nor how many
795  * bits match absolutely!).
796  *
797  * @param first the first hashcode
798  * @param second the hashcode to compare first to
799  * @return the number of bits that match
800  */
801 unsigned int
802 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
803                                   const struct GNUNET_HashCode *second);
804
805
806 /**
807  * @ingroup hash
808  * Compare function for HashCodes, producing a total ordering
809  * of all hashcodes.
810  *
811  * @param h1 some hash code
812  * @param h2 some hash code
813  * @return 1 if @a h1 > @a h2, -1 if @a h1 < @a h2 and 0 if @a h1 == @a h2.
814  */
815 int
816 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
817                         const struct GNUNET_HashCode *h2);
818
819
820 /**
821  * @ingroup hash
822  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
823  * in the XOR metric (Kademlia).
824  *
825  * @param h1 some hash code
826  * @param h2 some hash code
827  * @param target some hash code
828  * @return -1 if @a h1 is closer, 1 if @a h2 is closer and 0 if @a h1== @a h2.
829  */
830 int
831 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
832                            const struct GNUNET_HashCode *h2,
833                            const struct GNUNET_HashCode *target);
834
835
836 /**
837  * @ingroup hash
838  * @brief Derive an authentication key
839  * @param key authentication key
840  * @param rkey root key
841  * @param salt salt
842  * @param salt_len size of the salt
843  * @param argp pair of void * & size_t for context chunks, terminated by NULL
844  */
845 void
846 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
847                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
848                                  const void *salt, size_t salt_len,
849                                  va_list argp);
850
851
852 /**
853  * @ingroup hash
854  * @brief Derive an authentication key
855  * @param key authentication key
856  * @param rkey root key
857  * @param salt salt
858  * @param salt_len size of the salt
859  * @param ... pair of void * & size_t for context chunks, terminated by NULL
860  */
861 void
862 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
863                                const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
864                                const void *salt, size_t salt_len, ...);
865
866
867 /**
868  * @ingroup hash
869  * @brief Derive key
870  * @param result buffer for the derived key, allocated by caller
871  * @param out_len desired length of the derived key
872  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
873  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
874  * @param xts salt
875  * @param xts_len length of @a xts
876  * @param skm source key material
877  * @param skm_len length of @a skm
878  * @param ... pair of void * & size_t for context chunks, terminated by NULL
879  * @return #GNUNET_YES on success
880  */
881 int
882 GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo, int prf_algo,
883                     const void *xts, size_t xts_len, const void *skm,
884                     size_t skm_len, ...);
885
886
887 /**
888  * @ingroup hash
889  * @brief Derive key
890  * @param result buffer for the derived key, allocated by caller
891  * @param out_len desired length of the derived key
892  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
893  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
894  * @param xts salt
895  * @param xts_len length of @a xts
896  * @param skm source key material
897  * @param skm_len length of @a skm
898  * @param argp va_list of void * & size_t pairs for context chunks
899  * @return #GNUNET_YES on success
900  */
901 int
902 GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo, int prf_algo,
903                       const void *xts, size_t xts_len, const void *skm,
904                       size_t skm_len, va_list argp);
905
906
907 /**
908  * @brief Derive key
909  * @param result buffer for the derived key, allocated by caller
910  * @param out_len desired length of the derived key
911  * @param xts salt
912  * @param xts_len length of @a xts
913  * @param skm source key material
914  * @param skm_len length of @a skm
915  * @param argp va_list of void * & size_t pairs for context chunks
916  * @return #GNUNET_YES on success
917  */
918 int
919 GNUNET_CRYPTO_kdf_v (void *result, size_t out_len, const void *xts,
920                      size_t xts_len, const void *skm, size_t skm_len,
921                      va_list argp);
922
923
924 /**
925  * @ingroup hash
926  * @brief Derive key
927  * @param result buffer for the derived key, allocated by caller
928  * @param out_len desired length of the derived key
929  * @param xts salt
930  * @param xts_len length of @a xts
931  * @param skm source key material
932  * @param skm_len length of @a skm
933  * @param ... void * & size_t pairs for context chunks
934  * @return #GNUNET_YES on success
935  */
936 int
937 GNUNET_CRYPTO_kdf (void *result, size_t out_len, const void *xts,
938                    size_t xts_len, const void *skm, size_t skm_len, ...);
939
940
941 /**
942  * @ingroup crypto
943  * Extract the public key for the given private key.
944  *
945  * @param priv the private key
946  * @param pub where to write the public key
947  */
948 void
949 GNUNET_CRYPTO_ecdsa_key_get_public (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
950                                     struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
951
952 /**
953  * @ingroup crypto
954  * Extract the public key for the given private key.
955  *
956  * @param priv the private key
957  * @param pub where to write the public key
958  */
959 void
960 GNUNET_CRYPTO_eddsa_key_get_public (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
961                                     struct GNUNET_CRYPTO_EddsaPublicKey *pub);
962
963
964 /**
965  * @ingroup crypto
966  * Extract the public key for the given private key.
967  *
968  * @param priv the private key
969  * @param pub where to write the public key
970  */
971 void
972 GNUNET_CRYPTO_ecdhe_key_get_public (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
973                                     struct GNUNET_CRYPTO_EcdhePublicKey *pub);
974
975
976 /**
977  * Convert a public key to a string.
978  *
979  * @param pub key to convert
980  * @return string representing @a pub
981  */
982 char *
983 GNUNET_CRYPTO_ecdsa_public_key_to_string (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
984
985
986 /**
987  * Convert a public key to a string.
988  *
989  * @param pub key to convert
990  * @return string representing @a pub
991  */
992 char *
993 GNUNET_CRYPTO_eddsa_public_key_to_string (const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
994
995
996 /**
997  * Convert a string representing a public key to a public key.
998  *
999  * @param enc encoded public key
1000  * @param enclen number of bytes in @a enc (without 0-terminator)
1001  * @param pub where to store the public key
1002  * @return #GNUNET_OK on success
1003  */
1004 int
1005 GNUNET_CRYPTO_ecdsa_public_key_from_string (const char *enc,
1006                                             size_t enclen,
1007                                             struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1008
1009
1010 /**
1011  * Convert a string representing a public key to a public key.
1012  *
1013  * @param enc encoded public key
1014  * @param enclen number of bytes in @a enc (without 0-terminator)
1015  * @param pub where to store the public key
1016  * @return #GNUNET_OK on success
1017  */
1018 int
1019 GNUNET_CRYPTO_eddsa_public_key_from_string (const char *enc,
1020                                             size_t enclen,
1021                                             struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1022
1023
1024 /**
1025  * @ingroup crypto
1026  * Create a new private key by reading it from a file.  If the
1027  * files does not exist, create a new key and write it to the
1028  * file.  Caller must free return value.  Note that this function
1029  * can not guarantee that another process might not be trying
1030  * the same operation on the same file at the same time.
1031  * If the contents of the file
1032  * are invalid the old file is deleted and a fresh key is
1033  * created.
1034  *
1035  * @param filename name of file to use to store the key
1036  * @return new private key, NULL on error (for example,
1037  *   permission denied); free using #GNUNET_free
1038  */
1039 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1040 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename);
1041
1042
1043 /**
1044  * @ingroup crypto
1045  * Create a new private key by reading it from a file.  If the
1046  * files does not exist, create a new key and write it to the
1047  * file.  Caller must free return value.  Note that this function
1048  * can not guarantee that another process might not be trying
1049  * the same operation on the same file at the same time.
1050  * If the contents of the file
1051  * are invalid the old file is deleted and a fresh key is
1052  * created.
1053  *
1054  * @param filename name of file to use to store the key
1055  * @return new private key, NULL on error (for example,
1056  *   permission denied); free using #GNUNET_free
1057  */
1058 struct GNUNET_CRYPTO_EddsaPrivateKey *
1059 GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename);
1060
1061
1062 /**
1063  * @ingroup crypto
1064  * Create a new private key by reading our peer's key from
1065  * the file specified in the configuration.
1066  *
1067  * @param cfg the configuration to use
1068  * @return new private key, NULL on error (for example,
1069  *   permission denied); free using #GNUNET_free
1070  */
1071 struct GNUNET_CRYPTO_EddsaPrivateKey *
1072 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg);
1073
1074
1075 /**
1076  * @ingroup crypto
1077  * Create a new private key. Caller must free return value.
1078  *
1079  * @return fresh private key; free using #GNUNET_free
1080  */
1081 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1082 GNUNET_CRYPTO_ecdsa_key_create (void);
1083
1084
1085 /**
1086  * @ingroup crypto
1087  * Create a new private key. Caller must free return value.
1088  *
1089  * @return fresh private key; free using #GNUNET_free
1090  */
1091 struct GNUNET_CRYPTO_EddsaPrivateKey *
1092 GNUNET_CRYPTO_eddsa_key_create (void);
1093
1094
1095 /**
1096  * @ingroup crypto
1097  * Create a new private key. Caller must free return value.
1098  *
1099  * @return fresh private key; free using #GNUNET_free
1100  */
1101 struct GNUNET_CRYPTO_EcdhePrivateKey *
1102 GNUNET_CRYPTO_ecdhe_key_create (void);
1103
1104
1105 /**
1106  * @ingroup crypto
1107  * Clear memory that was used to store a private key.
1108  *
1109  * @param pk location of the key
1110  */
1111 void
1112 GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk);
1113
1114
1115 /**
1116  * @ingroup crypto
1117  * Clear memory that was used to store a private key.
1118  *
1119  * @param pk location of the key
1120  */
1121 void
1122 GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk);
1123
1124 /**
1125  * @ingroup crypto
1126  * Clear memory that was used to store a private key.
1127  *
1128  * @param pk location of the key
1129  */
1130 void
1131 GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk);
1132
1133
1134 /**
1135  * @ingroup crypto
1136  * Get the shared private key we use for anonymous users.
1137  *
1138  * @return "anonymous" private key; do not free
1139  */
1140 const struct GNUNET_CRYPTO_EcdsaPrivateKey *
1141 GNUNET_CRYPTO_ecdsa_key_get_anonymous (void);
1142
1143
1144 /**
1145  * @ingroup crypto
1146  * Setup a hostkey file for a peer given the name of the
1147  * configuration file (!).  This function is used so that
1148  * at a later point code can be certain that reading a
1149  * hostkey is fast (for example in time-dependent testcases).
1150 *
1151  * @param cfg_name name of the configuration file to use
1152  */
1153 void
1154 GNUNET_CRYPTO_eddsa_setup_hostkey (const char *cfg_name);
1155
1156
1157 /**
1158  * @ingroup crypto
1159  * Retrieve the identity of the host's peer.
1160  *
1161  * @param cfg configuration to use
1162  * @param dst pointer to where to write the peer identity
1163  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
1164  *         could not be retrieved
1165  */
1166 int
1167 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
1168                                  struct GNUNET_PeerIdentity *dst);
1169
1170 /**
1171  * Compare two Peer Identities.
1172  *
1173  * @param first first peer identity
1174  * @param second second peer identity
1175  * @return bigger than 0 if first > second,
1176  *         0 if they are the same
1177  *         smaller than 0 if second > first
1178  */
1179 int
1180 GNUNET_CRYPTO_cmp_peer_identity (const struct GNUNET_PeerIdentity *first,
1181                                  const struct GNUNET_PeerIdentity *second);
1182
1183
1184 /**
1185  * @ingroup crypto
1186  * Derive key material from a public and a private ECC key.
1187  *
1188  * @param priv private key to use for the ECDH (x)
1189  * @param pub public key to use for the ECDH (yG)
1190  * @param key_material where to write the key material (xyG)
1191  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1192  */
1193 int
1194 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1195                         const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1196                         struct GNUNET_HashCode *key_material);
1197
1198
1199 /**
1200  * @ingroup crypto
1201  * EdDSA sign a given block.
1202  *
1203  * @param priv private key to use for the signing
1204  * @param purpose what to sign (size, purpose)
1205  * @param sig where to write the signature
1206  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1207  */
1208 int
1209 GNUNET_CRYPTO_eddsa_sign (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1210                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1211                           struct GNUNET_CRYPTO_EddsaSignature *sig);
1212
1213
1214 /**
1215  * @ingroup crypto
1216  * ECDSA Sign a given block.
1217  *
1218  * @param priv private key to use for the signing
1219  * @param purpose what to sign (size, purpose)
1220  * @param sig where to write the signature
1221  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1222  */
1223 int
1224 GNUNET_CRYPTO_ecdsa_sign (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1225                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1226                           struct GNUNET_CRYPTO_EcdsaSignature *sig);
1227
1228 /**
1229  * @ingroup crypto
1230  * Verify EdDSA signature.
1231  *
1232  * @param purpose what is the purpose that the signature should have?
1233  * @param validate block to validate (size, purpose, data)
1234  * @param sig signature that is being validated
1235  * @param pub public key of the signer
1236  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1237  */
1238 int
1239 GNUNET_CRYPTO_eddsa_verify (uint32_t purpose,
1240                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1241                             const struct GNUNET_CRYPTO_EddsaSignature *sig,
1242                             const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1243
1244
1245
1246 /**
1247  * @ingroup crypto
1248  * Verify ECDSA signature.
1249  *
1250  * @param purpose what is the purpose that the signature should have?
1251  * @param validate block to validate (size, purpose, data)
1252  * @param sig signature that is being validated
1253  * @param pub public key of the signer
1254  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1255  */
1256 int
1257 GNUNET_CRYPTO_ecdsa_verify (uint32_t purpose,
1258                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1259                             const struct GNUNET_CRYPTO_EcdsaSignature *sig,
1260                             const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1261
1262
1263 /**
1264  * @ingroup crypto
1265  * Derive a private key from a given private key and a label.
1266  * Essentially calculates a private key 'h = H(l,P) * d mod n'
1267  * where n is the size of the ECC group and P is the public
1268  * key associated with the private key 'd'.
1269  *
1270  * @param priv original private key
1271  * @param label label to use for key deriviation
1272  * @param context additional context to use for HKDF of 'h';
1273  *        typically the name of the subsystem/application
1274  * @return derived private key
1275  */
1276 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1277 GNUNET_CRYPTO_ecdsa_private_key_derive (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1278                                         const char *label,
1279                                         const char *context);
1280
1281
1282 /**
1283  * @ingroup crypto
1284  * Derive a public key from a given public key and a label.
1285  * Essentially calculates a public key 'V = H(l,P) * P'.
1286  *
1287  * @param pub original public key
1288  * @param label label to use for key deriviation
1289  * @param context additional context to use for HKDF of 'h'.
1290  *        typically the name of the subsystem/application
1291  * @param result where to write the derived public key
1292  */
1293 void
1294 GNUNET_CRYPTO_ecdsa_public_key_derive (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1295                                        const char *label,
1296                                        const char *context,
1297                                        struct GNUNET_CRYPTO_EcdsaPublicKey *result);
1298
1299
1300 /**
1301  * Output the given MPI value to the given buffer in network
1302  * byte order.  The MPI @a val may not be negative.
1303  *
1304  * @param buf where to output to
1305  * @param size number of bytes in @a buf
1306  * @param val value to write to @a buf
1307  */
1308 void
1309 GNUNET_CRYPTO_mpi_print_unsigned (void *buf,
1310                                   size_t size,
1311                                   gcry_mpi_t val);
1312
1313
1314 /**
1315  * Convert data buffer into MPI value.
1316  * The buffer is interpreted as network
1317  * byte order, unsigned integer.
1318  *
1319  * @param result where to store MPI value (allocated)
1320  * @param data raw data (GCRYMPI_FMT_USG)
1321  * @param size number of bytes in @a data
1322  */
1323 void
1324 GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result,
1325                                  const void *data,
1326                                  size_t size);
1327
1328
1329 /**
1330  * Create a freshly generated paillier public key.
1331  *
1332  * @param[out] public_key Where to store the public key?
1333  * @param[out] private_key Where to store the private key?
1334  */
1335 void
1336 GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1337                                struct GNUNET_CRYPTO_PaillierPrivateKey *private_key);
1338
1339
1340 /**
1341  * Encrypt a plaintext with a paillier public key.
1342  *
1343  * @param public_key Public key to use.
1344  * @param plaintext Plaintext to encrypt.
1345  * @param[out] ciphertext Encrytion of @a plaintext with @a public_key.
1346  */
1347 void
1348 GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1349                                 const gcry_mpi_t m,
1350                                 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext);
1351
1352
1353 /**
1354  * Decrypt a paillier ciphertext with a private key.
1355  *
1356  * @param private_key Private key to use for decryption.
1357  * @param public_key Public key to use for decryption.
1358  * @param ciphertext Ciphertext to decrypt.
1359  * @param[out] plaintext Decryption of @a ciphertext with @private_key.
1360  */
1361 void
1362 GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key,
1363                                 const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1364                                 const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext,
1365                                 gcry_mpi_t m);
1366
1367
1368 /**
1369  * Compute a ciphertext that represents the sum of the plaintext in @a x1 and @a x2
1370  *
1371  * Note that this operation can only be done a finite number of times
1372  * before an overflow occurs.
1373  *
1374  * @param x1 Paillier cipher text.
1375  * @param x2 Paillier cipher text.
1376  * @param[out] result Result of the homomorphic operation.
1377  * @return #GNUNET_OK if the result could be computed,
1378  *         #GNUNET_SYSERR if no more homomorphic operations are remaining.
1379  */
1380 int
1381 GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierCiphertext *x1,
1382                                 const struct GNUNET_CRYPTO_PaillierCiphertext *x2,
1383                                 const struct GNUNET_CRYPTO_PaillierCiphertext *result);
1384
1385
1386 #if 0                           /* keep Emacsens' auto-indent happy */
1387 {
1388 #endif
1389 #ifdef __cplusplus
1390 }
1391 #endif
1392
1393
1394 /* ifndef GNUNET_CRYPTO_LIB_H */
1395 #endif
1396 /* end of gnunet_crypto_lib.h */