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