glitch in the license text detected by hyazinthe, thank you!
[oweals/gnunet.git] / src / include / gnunet_crypto_lib.h
1 /*
2      This file is part of GNUnet.
3      Copyright (C) 2001-2013 GNUnet e.V.
4
5      GNUnet is free software: you can redistribute it and/or modify it
6      under the terms of the GNU Affero General Public License as published
7      by the Free Software Foundation, either version 3 of the License,
8      or (at your 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      Affero General Public License for more details.
14 */
15
16 /**
17  * @file include/gnunet_crypto_lib.h
18  * @brief cryptographic primitives for GNUnet
19  *
20  * @author Christian Grothoff
21  * @author Krista Bennett
22  * @author Gerd Knorr <kraxel@bytesex.org>
23  * @author Ioana Patrascu
24  * @author Tzvetan Horozov
25  * @author Jeffrey Burdges <burdges@gnunet.org>
26  *
27  * @defgroup crypto  Crypto library: cryptographic operations
28  * Provides cryptographic primitives.
29  *
30  * @see [Documentation](https://gnunet.org/crypto-api)
31  *
32  * @defgroup hash  Crypto library: hash operations
33  * Provides hashing and operations on hashes.
34  *
35  * @see [Documentation](https://gnunet.org/crypto-api)
36  */
37
38 #ifndef GNUNET_CRYPTO_LIB_H
39 #define GNUNET_CRYPTO_LIB_H
40
41 #ifdef __cplusplus
42 extern "C"
43 {
44 #if 0                           /* keep Emacsens' auto-indent happy */
45 }
46 #endif
47 #endif
48
49 /**
50  * @brief A 512-bit hashcode.  These are the default length for GNUnet, using SHA-512.
51  */
52 struct GNUNET_HashCode
53 {
54   uint32_t bits[512 / 8 / sizeof (uint32_t)];   /* = 16 */
55 };
56
57
58
59 /**
60  * @brief A 256-bit hashcode.  Used under special conditions, like when space
61  * is critical and security is not impacted by it.
62  */
63 struct GNUNET_ShortHashCode
64 {
65   uint32_t bits[256 / 8 / sizeof (uint32_t)];   /* = 8 */
66 };
67
68
69 /**
70  * The identity of the host (wraps the signing key of the peer).
71  */
72 struct GNUNET_PeerIdentity;
73
74 #include "gnunet_common.h"
75 #include <gcrypt.h>
76
77
78 /**
79  * Maximum length of an ECC signature.
80  * Note: round up to multiple of 8 minus 2 for alignment.
81  */
82 #define GNUNET_CRYPTO_ECC_SIGNATURE_DATA_ENCODING_LENGTH 126
83
84
85 /**
86  * Desired quality level for random numbers.
87  * @ingroup crypto
88  */
89 enum GNUNET_CRYPTO_Quality
90 {
91   /**
92    * No good quality of the operation is needed (i.e.,
93    * random numbers can be pseudo-random).
94    * @ingroup crypto
95    */
96   GNUNET_CRYPTO_QUALITY_WEAK,
97
98   /**
99    * High-quality operations are desired.
100    * @ingroup crypto
101    */
102   GNUNET_CRYPTO_QUALITY_STRONG,
103
104   /**
105    * Randomness for IVs etc. is required.
106    * @ingroup crypto
107    */
108   GNUNET_CRYPTO_QUALITY_NONCE
109 };
110
111
112 /**
113  * @brief length of the sessionkey in bytes (256 BIT sessionkey)
114  */
115 #define GNUNET_CRYPTO_AES_KEY_LENGTH (256/8)
116
117 /**
118  * Length of a hash value
119  */
120 #define GNUNET_CRYPTO_HASH_LENGTH (512/8)
121
122 /**
123  * How many characters (without 0-terminator) are our ASCII-encoded
124  * public keys (ECDSA/EDDSA/ECDHE).
125  */
126 #define GNUNET_CRYPTO_PKEY_ASCII_LENGTH 52
127
128 /**
129  * @brief 0-terminated ASCII encoding of a struct GNUNET_HashCode.
130  */
131 struct GNUNET_CRYPTO_HashAsciiEncoded
132 {
133   unsigned char encoding[104];
134 };
135
136
137 GNUNET_NETWORK_STRUCT_BEGIN
138
139
140 /**
141  * @brief header of what an ECC signature signs
142  *        this must be followed by "size - 8" bytes of
143  *        the actual signed data
144  */
145 struct GNUNET_CRYPTO_EccSignaturePurpose
146 {
147   /**
148    * How many bytes does this signature sign?
149    * (including this purpose header); in network
150    * byte order (!).
151    */
152   uint32_t size GNUNET_PACKED;
153
154   /**
155    * What does this signature vouch for?  This
156    * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
157    * constant (from gnunet_signatures.h).  In
158    * network byte order!
159    */
160   uint32_t purpose GNUNET_PACKED;
161
162 };
163
164
165 /**
166  * @brief an ECC signature using EdDSA.
167  * See https://gnunet.org/ed25519
168  */
169 struct GNUNET_CRYPTO_EddsaSignature
170 {
171
172   /**
173    * R value.
174    */
175   unsigned char r[256 / 8];
176
177   /**
178    * S value.
179    */
180   unsigned char s[256 / 8];
181
182 };
183
184
185
186 /**
187  * @brief an ECC signature using ECDSA
188  */
189 struct GNUNET_CRYPTO_EcdsaSignature
190 {
191
192   /**
193    * R value.
194    */
195   unsigned char r[256 / 8];
196
197   /**
198    * S value.
199    */
200   unsigned char s[256 / 8];
201
202 };
203
204
205 /**
206  * Public ECC key (always for Curve25519) encoded in a format suitable
207  * for network transmission and EdDSA signatures.
208  */
209 struct GNUNET_CRYPTO_EddsaPublicKey
210 {
211   /**
212    * Q consists of an x- and a y-value, each mod p (256 bits), given
213    * here in affine coordinates and Ed25519 standard compact format.
214    */
215   unsigned char q_y[256 / 8];
216
217 };
218
219
220 /**
221  * Public ECC key (always for Curve25519) encoded in a format suitable
222  * for network transmission and ECDSA signatures.
223  */
224 struct GNUNET_CRYPTO_EcdsaPublicKey
225 {
226   /**
227    * Q consists of an x- and a y-value, each mod p (256 bits), given
228    * here in affine coordinates and Ed25519 standard compact format.
229    */
230   unsigned char q_y[256 / 8];
231
232 };
233
234
235 /**
236  * The identity of the host (wraps the signing key of the peer).
237  */
238 struct GNUNET_PeerIdentity
239 {
240   struct GNUNET_CRYPTO_EddsaPublicKey public_key;
241 };
242
243
244 /**
245  * Public ECC key (always for Curve25519) encoded in a format suitable
246  * for network transmission and encryption (ECDH),
247  * See http://cr.yp.to/ecdh.html
248  */
249 struct GNUNET_CRYPTO_EcdhePublicKey
250 {
251   /**
252    * Q consists of an x- and a y-value, each mod p (256 bits), given
253    * here in affine coordinates and Ed25519 standard compact format.
254    */
255   unsigned char q_y[256 / 8];
256 };
257
258
259 /**
260  * Private ECC key encoded for transmission.  To be used only for ECDH
261  * key exchange (ECDHE to be precise).
262  */
263 struct GNUNET_CRYPTO_EcdhePrivateKey
264 {
265   /**
266    * d is a value mod n, where n has at most 256 bits.
267    */
268   unsigned char d[256 / 8];
269
270 };
271
272 /**
273  * Private ECC key encoded for transmission.  To be used only for ECDSA
274  * signatures.
275  */
276 struct GNUNET_CRYPTO_EcdsaPrivateKey
277 {
278   /**
279    * d is a value mod n, where n has at most 256 bits.
280    */
281   unsigned char d[256 / 8];
282
283 };
284
285 /**
286  * Private ECC key encoded for transmission.  To be used only for EdDSA
287  * signatures.
288  */
289 struct GNUNET_CRYPTO_EddsaPrivateKey
290 {
291   /**
292    * d is a value mod n, where n has at most 256 bits.
293    */
294   unsigned char d[256 / 8];
295
296 };
297
298
299 /**
300  * @brief type for session keys
301  */
302 struct GNUNET_CRYPTO_SymmetricSessionKey
303 {
304   /**
305    * Actual key for AES.
306    */
307   unsigned char aes_key[GNUNET_CRYPTO_AES_KEY_LENGTH];
308
309   /**
310    * Actual key for TwoFish.
311    */
312   unsigned char twofish_key[GNUNET_CRYPTO_AES_KEY_LENGTH];
313
314 };
315
316 GNUNET_NETWORK_STRUCT_END
317
318 /**
319  * @brief IV for sym cipher
320  *
321  * NOTE: must be smaller (!) in size than the
322  * `struct GNUNET_HashCode`.
323  */
324 struct GNUNET_CRYPTO_SymmetricInitializationVector
325 {
326   unsigned char aes_iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
327
328   unsigned char twofish_iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
329 };
330
331
332 /**
333  * @brief type for (message) authentication keys
334  */
335 struct GNUNET_CRYPTO_AuthKey
336 {
337   unsigned char key[GNUNET_CRYPTO_HASH_LENGTH];
338 };
339
340
341 /**
342  * Size of paillier plain texts and public keys.
343  * Private keys and ciphertexts are twice this size.
344  */
345 #define GNUNET_CRYPTO_PAILLIER_BITS 2048
346
347
348 /**
349  * Paillier public key.
350  */
351 struct GNUNET_CRYPTO_PaillierPublicKey
352 {
353   /**
354    * N value.
355    */
356   unsigned char n[GNUNET_CRYPTO_PAILLIER_BITS / 8];
357 };
358
359
360 /**
361  * Paillier private key.
362  */
363 struct GNUNET_CRYPTO_PaillierPrivateKey
364 {
365   /**
366    * Lambda-component of the private key.
367    */
368   unsigned char lambda[GNUNET_CRYPTO_PAILLIER_BITS / 8];
369   /**
370    * Mu-component of the private key.
371    */
372   unsigned char mu[GNUNET_CRYPTO_PAILLIER_BITS / 8];
373 };
374
375
376 /**
377  * Paillier ciphertext.
378  */
379 struct GNUNET_CRYPTO_PaillierCiphertext
380 {
381   /**
382    * Guaranteed minimum number of homomorphic operations with this ciphertext,
383    * in network byte order (NBO).
384    */
385   int32_t remaining_ops GNUNET_PACKED;
386
387   /**
388    * The bits of the ciphertext.
389    */
390   unsigned char bits[GNUNET_CRYPTO_PAILLIER_BITS * 2 / 8];
391 };
392
393
394 /* **************** Functions and Macros ************* */
395
396 /**
397  * @ingroup crypto
398  * Seed a weak random generator. Only #GNUNET_CRYPTO_QUALITY_WEAK-mode generator
399  * can be seeded.
400  *
401  * @param seed the seed to use
402  */
403 void
404 GNUNET_CRYPTO_seed_weak_random (int32_t seed);
405
406
407 /**
408  * @ingroup hash
409  * Calculate the checksum of a buffer in one step.
410  *
411  * @param buf buffer to calculate CRC over
412  * @param len number of bytes in @a buf
413  * @return crc8 value
414  */
415 uint8_t
416 GNUNET_CRYPTO_crc8_n (const void *buf,
417                       size_t len);
418
419
420 /**
421  * Perform an incremental step in a CRC16 (for TCP/IP) calculation.
422  *
423  * @param sum current sum, initially 0
424  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
425  * @param len number of bytes in @a buf, must be multiple of 2
426  * @return updated crc sum (must be subjected to #GNUNET_CRYPTO_crc16_finish to get actual crc16)
427  */
428 uint32_t
429 GNUNET_CRYPTO_crc16_step (uint32_t sum,
430                           const void *buf,
431                           size_t len);
432
433
434 /**
435  * Convert results from GNUNET_CRYPTO_crc16_step to final crc16.
436  *
437  * @param sum cummulative sum
438  * @return crc16 value
439  */
440 uint16_t
441 GNUNET_CRYPTO_crc16_finish (uint32_t sum);
442
443
444 /**
445  * @ingroup hash
446  * Calculate the checksum of a buffer in one step.
447  *
448  * @param buf buffer to calculate CRC over (must be 16-bit aligned)
449  * @param len number of bytes in @a buf, must be multiple of 2
450  * @return crc16 value
451  */
452 uint16_t
453 GNUNET_CRYPTO_crc16_n (const void *buf,
454                        size_t len);
455
456
457
458
459 /**
460  * @ingroup hash
461  * Compute the CRC32 checksum for the first len
462  * bytes of the buffer.
463  *
464  * @param buf the data over which we're taking the CRC
465  * @param len the length of the buffer @a buf in bytes
466  * @return the resulting CRC32 checksum
467  */
468 int32_t
469 GNUNET_CRYPTO_crc32_n (const void *buf,
470                        size_t len);
471
472
473 /**
474  * @ingroup crypto
475  * Fill block with a random values.
476  *
477  * @param mode desired quality of the random number
478  * @param buffer the buffer to fill
479  * @param length buffer length
480  */
481 void
482 GNUNET_CRYPTO_random_block (enum GNUNET_CRYPTO_Quality mode,
483                             void *buffer,
484                             size_t length);
485
486 /**
487  * @ingroup crypto
488  * Produce a random value.
489  *
490  * @param mode desired quality of the random number
491  * @param i the upper limit (exclusive) for the random number
492  * @return a random value in the interval [0,@a i) (exclusive).
493  */
494 uint32_t
495 GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode,
496                           uint32_t i);
497
498
499 /**
500  * @ingroup crypto
501  * Random on unsigned 64-bit values.
502  *
503  * @param mode desired quality of the random number
504  * @param max value returned will be in range [0,@a max) (exclusive)
505  * @return random 64-bit number
506  */
507 uint64_t
508 GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode,
509                           uint64_t max);
510
511
512 /**
513  * @ingroup crypto
514  * Get an array with a random permutation of the
515  * numbers 0...n-1.
516  * @param mode #GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used,
517  *             #GNUNET_CRYPTO_QUALITY_WEAK or #GNUNET_CRYPTO_QUALITY_NONCE otherwise
518  * @param n the size of the array
519  * @return the permutation array (allocated from heap)
520  */
521 unsigned int *
522 GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
523                               unsigned int n);
524
525
526 /**
527  * @ingroup crypto
528  * Create a new random session key.
529  *
530  * @param key key to initialize
531  */
532 void
533 GNUNET_CRYPTO_symmetric_create_session_key (struct GNUNET_CRYPTO_SymmetricSessionKey *key);
534
535
536 /**
537  * @ingroup crypto
538  * Encrypt a block using a symmetric sessionkey.
539  *
540  * @param block the block to encrypt
541  * @param size the size of the @a block
542  * @param sessionkey the key used to encrypt
543  * @param iv the initialization vector to use, use INITVALUE
544  *        for streams.
545  * @return the size of the encrypted block, -1 for errors
546  */
547 ssize_t
548 GNUNET_CRYPTO_symmetric_encrypt (const void *block,
549                                  size_t size,
550                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
551                                  const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
552                                  void *result);
553
554
555 /**
556  * @ingroup crypto
557  * Decrypt a given block using a symmetric sessionkey.
558  *
559  * @param block the data to decrypt, encoded as returned by encrypt
560  * @param size how big is the block?
561  * @param sessionkey the key used to decrypt
562  * @param iv the initialization vector to use
563  * @param result address to store the result at
564  * @return -1 on failure, size of decrypted block on success
565  */
566 ssize_t
567 GNUNET_CRYPTO_symmetric_decrypt (const void *block,
568                                  size_t size,
569                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *sessionkey,
570                                  const struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
571                                  void *result);
572
573
574 /**
575  * @ingroup crypto
576  * @brief Derive an IV
577  * @param iv initialization vector
578  * @param skey session key
579  * @param salt salt for the derivation
580  * @param salt_len size of the @a salt
581  * @param ... pairs of void * & size_t for context chunks, terminated by NULL
582  */
583 void
584 GNUNET_CRYPTO_symmetric_derive_iv (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
585                                    const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
586                                    const void *salt,
587                                    size_t salt_len, ...);
588
589
590 /**
591  * @brief Derive an IV
592  * @param iv initialization vector
593  * @param skey session key
594  * @param salt salt for the derivation
595  * @param salt_len size of the @a salt
596  * @param argp pairs of void * & size_t for context chunks, terminated by NULL
597  */
598 void
599 GNUNET_CRYPTO_symmetric_derive_iv_v (struct GNUNET_CRYPTO_SymmetricInitializationVector *iv,
600                                      const struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
601                                      const void *salt,
602                                      size_t salt_len,
603                                      va_list argp);
604
605
606 /**
607  * @ingroup hash
608  * Convert hash to ASCII encoding.
609  * @param block the hash code
610  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
611  *  safely cast to char*, a '\\0' termination is set).
612  */
613 void
614 GNUNET_CRYPTO_hash_to_enc (const struct GNUNET_HashCode *block,
615                            struct GNUNET_CRYPTO_HashAsciiEncoded *result);
616
617
618 /**
619  * @ingroup hash
620  * Convert ASCII encoding back to a 'struct GNUNET_HashCode'
621  *
622  * @param enc the encoding
623  * @param enclen number of characters in @a enc (without 0-terminator, which can be missing)
624  * @param result where to store the hash code
625  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
626  */
627 int
628 GNUNET_CRYPTO_hash_from_string2 (const char *enc,
629                                  size_t enclen,
630                                  struct GNUNET_HashCode *result);
631
632
633 /**
634  * @ingroup hash
635  * Convert ASCII encoding back to `struct GNUNET_HashCode`
636  *
637  * @param enc the encoding
638  * @param result where to store the hash code
639  * @return #GNUNET_OK on success, #GNUNET_SYSERR if result has the wrong encoding
640  */
641 #define GNUNET_CRYPTO_hash_from_string(enc, result) \
642   GNUNET_CRYPTO_hash_from_string2 (enc, strlen(enc), result)
643
644
645 /**
646  * @ingroup hash
647  *
648  * Compute the distance between 2 hashcodes.  The
649  * computation must be fast, not involve @a a[0] or @a a[4] (they're used
650  * elsewhere), and be somewhat consistent. And of course, the result
651  * should be a positive number.
652  *
653  * @param a some hash code
654  * @param b some hash code
655  * @return number between 0 and UINT32_MAX
656  */
657 uint32_t
658 GNUNET_CRYPTO_hash_distance_u32 (const struct GNUNET_HashCode *a,
659                                  const struct GNUNET_HashCode *b);
660
661
662 /**
663  * @ingroup hash
664  * Compute hash of a given block.
665  *
666  * @param block the data to hash
667  * @param size size of the @a block
668  * @param ret pointer to where to write the hashcode
669  */
670 void
671 GNUNET_CRYPTO_hash (const void *block,
672                     size_t size,
673                     struct GNUNET_HashCode *ret);
674
675
676 /**
677  * Context for cummulative hashing.
678  */
679 struct GNUNET_HashContext;
680
681
682 /**
683  * Start incremental hashing operation.
684  *
685  * @return context for incremental hash computation
686  */
687 struct GNUNET_HashContext *
688 GNUNET_CRYPTO_hash_context_start (void);
689
690
691 /**
692  * Add data to be hashed.
693  *
694  * @param hc cummulative hash context
695  * @param buf data to add
696  * @param size number of bytes in @a buf
697  */
698 void
699 GNUNET_CRYPTO_hash_context_read (struct GNUNET_HashContext *hc,
700                                  const void *buf,
701                                  size_t size);
702
703
704 /**
705  * Finish the hash computation.
706  *
707  * @param hc hash context to use, is freed in the process
708  * @param r_hash where to write the latest / final hash code
709  */
710 void
711 GNUNET_CRYPTO_hash_context_finish (struct GNUNET_HashContext *hc,
712                                    struct GNUNET_HashCode *r_hash);
713
714
715 /**
716  * Abort hashing, do not bother calculating final result.
717  *
718  * @param hc hash context to destroy
719  */
720 void
721 GNUNET_CRYPTO_hash_context_abort (struct GNUNET_HashContext *hc);
722
723
724 /**
725  * @ingroup hash
726  * Calculate HMAC of a message (RFC 2104)
727  *
728  * @param key secret key
729  * @param plaintext input plaintext
730  * @param plaintext_len length of @a plaintext
731  * @param hmac where to store the hmac
732  */
733 void
734 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
735                     const void *plaintext,
736                     size_t plaintext_len,
737                     struct GNUNET_HashCode *hmac);
738
739
740 /**
741  * Function called once the hash computation over the
742  * specified file has completed.
743  *
744  * @param cls closure
745  * @param res resulting hash, NULL on error
746  */
747 typedef void
748 (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
749                                         const struct GNUNET_HashCode *res);
750
751
752 /**
753  * Handle to file hashing operation.
754  */
755 struct GNUNET_CRYPTO_FileHashContext;
756
757
758 /**
759  * @ingroup hash
760  * Compute the hash of an entire file.
761  *
762  * @param priority scheduling priority to use
763  * @param filename name of file to hash
764  * @param blocksize number of bytes to process in one task
765  * @param callback function to call upon completion
766  * @param callback_cls closure for @a callback
767  * @return NULL on (immediate) errror
768  */
769 struct GNUNET_CRYPTO_FileHashContext *
770 GNUNET_CRYPTO_hash_file (enum GNUNET_SCHEDULER_Priority priority,
771                          const char *filename,
772                          size_t blocksize,
773                          GNUNET_CRYPTO_HashCompletedCallback callback,
774                          void *callback_cls);
775
776
777 /**
778  * Cancel a file hashing operation.
779  *
780  * @param fhc operation to cancel (callback must not yet have been invoked)
781  */
782 void
783 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
784
785
786 /**
787  * @ingroup hash
788  * Create a random hash code.
789  *
790  * @param mode desired quality level
791  * @param result hash code that is randomized
792  */
793 void
794 GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
795                                   struct GNUNET_HashCode *result);
796
797
798 /**
799  * @ingroup hash
800  * compute @a result = @a b - @a a
801  *
802  * @param a some hash code
803  * @param b some hash code
804  * @param result set to @a b - @a a
805  */
806 void
807 GNUNET_CRYPTO_hash_difference (const struct GNUNET_HashCode *a,
808                                const struct GNUNET_HashCode *b,
809                                struct GNUNET_HashCode *result);
810
811
812 /**
813  * @ingroup hash
814  * compute @a result = @a a + @a delta
815  *
816  * @param a some hash code
817  * @param delta some hash code
818  * @param result set to @a a + @a delta
819  */
820 void
821 GNUNET_CRYPTO_hash_sum (const struct GNUNET_HashCode *a,
822                         const struct GNUNET_HashCode *delta,
823                         struct GNUNET_HashCode *result);
824
825
826 /**
827  * @ingroup hash
828  * compute result = a ^ b
829  *
830  * @param a some hash code
831  * @param b some hash code
832  * @param result set to @a a ^ @a b
833  */
834 void
835 GNUNET_CRYPTO_hash_xor (const struct GNUNET_HashCode *a,
836                         const struct GNUNET_HashCode *b,
837                         struct GNUNET_HashCode *result);
838
839
840 /**
841  * @ingroup hash
842  * Convert a hashcode into a key.
843  *
844  * @param hc hash code that serves to generate the key
845  * @param skey set to a valid session key
846  * @param iv set to a valid initialization vector
847  */
848 void
849 GNUNET_CRYPTO_hash_to_aes_key (const struct GNUNET_HashCode * hc,
850                                struct GNUNET_CRYPTO_SymmetricSessionKey *skey,
851                                struct GNUNET_CRYPTO_SymmetricInitializationVector *iv);
852
853
854 /**
855  * @ingroup hash
856  * Obtain a bit from a hashcode.
857  *
858  * @param code the `struct GNUNET_HashCode` to index bit-wise
859  * @param bit index into the hashcode, [0...159]
860  * @return Bit \a bit from hashcode \a code, -1 for invalid index
861  */
862 int
863 GNUNET_CRYPTO_hash_get_bit (const struct GNUNET_HashCode *code,
864                             unsigned int bit);
865
866
867 /**
868  * @ingroup hash
869  * Determine how many low order bits match in two
870  * `struct GNUNET_HashCodes`.  i.e. - 010011 and 011111 share
871  * the first two lowest order bits, and therefore the
872  * return value is two (NOT XOR distance, nor how many
873  * bits match absolutely!).
874  *
875  * @param first the first hashcode
876  * @param second the hashcode to compare first to
877  * @return the number of bits that match
878  */
879 unsigned int
880 GNUNET_CRYPTO_hash_matching_bits (const struct GNUNET_HashCode *first,
881                                   const struct GNUNET_HashCode *second);
882
883
884 /**
885  * @ingroup hash
886  * Compare function for HashCodes, producing a total ordering
887  * of all hashcodes.
888  *
889  * @param h1 some hash code
890  * @param h2 some hash code
891  * @return 1 if @a h1 > @a h2, -1 if @a h1 < @a h2 and 0 if @a h1 == @a h2.
892  */
893 int
894 GNUNET_CRYPTO_hash_cmp (const struct GNUNET_HashCode *h1,
895                         const struct GNUNET_HashCode *h2);
896
897
898 /**
899  * @ingroup hash
900  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
901  * in the XOR metric (Kademlia).
902  *
903  * @param h1 some hash code
904  * @param h2 some hash code
905  * @param target some hash code
906  * @return -1 if @a h1 is closer, 1 if @a h2 is closer and 0 if @a h1== @a h2.
907  */
908 int
909 GNUNET_CRYPTO_hash_xorcmp (const struct GNUNET_HashCode *h1,
910                            const struct GNUNET_HashCode *h2,
911                            const struct GNUNET_HashCode *target);
912
913
914 /**
915  * @ingroup hash
916  * @brief Derive an authentication key
917  * @param key authentication key
918  * @param rkey root key
919  * @param salt salt
920  * @param salt_len size of the salt
921  * @param argp pair of void * & size_t for context chunks, terminated by NULL
922  */
923 void
924 GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
925                                  const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
926                                  const void *salt, size_t salt_len,
927                                  va_list argp);
928
929
930 /**
931  * @ingroup hash
932  * @brief Derive an authentication key
933  * @param key authentication key
934  * @param rkey root key
935  * @param salt salt
936  * @param salt_len size of the salt
937  * @param ... pair of void * & size_t for context chunks, terminated by NULL
938  */
939 void
940 GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
941                                const struct GNUNET_CRYPTO_SymmetricSessionKey *rkey,
942                                const void *salt, size_t salt_len,
943                                ...);
944
945
946 /**
947  * @ingroup hash
948  * @brief Derive key
949  * @param result buffer for the derived key, allocated by caller
950  * @param out_len desired length of the derived key
951  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
952  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
953  * @param xts salt
954  * @param xts_len length of @a xts
955  * @param skm source key material
956  * @param skm_len length of @a skm
957  * @param ... pair of void * & size_t for context chunks, terminated by NULL
958  * @return #GNUNET_YES on success
959  */
960 int
961 GNUNET_CRYPTO_hkdf (void *result,
962                     size_t out_len,
963                     int xtr_algo,
964                     int prf_algo,
965                     const void *xts,
966                     size_t xts_len,
967                     const void *skm,
968                     size_t skm_len,
969                     ...);
970
971
972 /**
973  * @ingroup hash
974  * @brief Derive key
975  * @param result buffer for the derived key, allocated by caller
976  * @param out_len desired length of the derived key
977  * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
978  * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
979  * @param xts salt
980  * @param xts_len length of @a xts
981  * @param skm source key material
982  * @param skm_len length of @a skm
983  * @param argp va_list of void * & size_t pairs for context chunks
984  * @return #GNUNET_YES on success
985  */
986 int
987 GNUNET_CRYPTO_hkdf_v (void *result,
988                       size_t out_len,
989                       int xtr_algo,
990                       int prf_algo,
991                       const void *xts,
992                       size_t xts_len,
993                       const void *skm,
994                       size_t skm_len,
995                       va_list argp);
996
997
998 /**
999  * @brief Derive key
1000  * @param result buffer for the derived key, allocated by caller
1001  * @param out_len desired length of the derived key
1002  * @param xts salt
1003  * @param xts_len length of @a xts
1004  * @param skm source key material
1005  * @param skm_len length of @a skm
1006  * @param argp va_list of void * & size_t pairs for context chunks
1007  * @return #GNUNET_YES on success
1008  */
1009 int
1010 GNUNET_CRYPTO_kdf_v (void *result,
1011                      size_t out_len,
1012                      const void *xts,
1013                      size_t xts_len,
1014                      const void *skm,
1015                      size_t skm_len,
1016                      va_list argp);
1017
1018
1019 /**
1020  * Deterministically generate a pseudo-random number uniformly from the
1021  * integers modulo a libgcrypt mpi.
1022  *
1023  * @param[out] r MPI value set to the FDH
1024  * @param n MPI to work modulo
1025  * @param xts salt
1026  * @param xts_len length of @a xts
1027  * @param skm source key material
1028  * @param skm_len length of @a skm
1029  * @param ctx context string
1030  */
1031 void
1032 GNUNET_CRYPTO_kdf_mod_mpi (gcry_mpi_t *r,
1033                            gcry_mpi_t n,
1034                            const void *xts,  size_t xts_len,
1035                            const void *skm,  size_t skm_len,
1036                            const char *ctx);
1037
1038
1039 /**
1040  * @ingroup hash
1041  * @brief Derive key
1042  * @param result buffer for the derived key, allocated by caller
1043  * @param out_len desired length of the derived key
1044  * @param xts salt
1045  * @param xts_len length of @a xts
1046  * @param skm source key material
1047  * @param skm_len length of @a skm
1048  * @param ... void * & size_t pairs for context chunks
1049  * @return #GNUNET_YES on success
1050  */
1051 int
1052 GNUNET_CRYPTO_kdf (void *result,
1053                    size_t out_len,
1054                    const void *xts,
1055                    size_t xts_len,
1056                    const void *skm,
1057                    size_t skm_len,
1058                    ...);
1059
1060
1061 /**
1062  * @ingroup crypto
1063  * Extract the public key for the given private key.
1064  *
1065  * @param priv the private key
1066  * @param pub where to write the public key
1067  */
1068 void
1069 GNUNET_CRYPTO_ecdsa_key_get_public (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1070                                     struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1071
1072 /**
1073  * @ingroup crypto
1074  * Extract the public key for the given private key.
1075  *
1076  * @param priv the private key
1077  * @param pub where to write the public key
1078  */
1079 void
1080 GNUNET_CRYPTO_eddsa_key_get_public (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1081                                     struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1082
1083
1084
1085 /**
1086  * @ingroup crypto
1087  * Extract the public key for the given private key.
1088  *
1089  * @param priv the private key
1090  * @param pub where to write the public key
1091  */
1092 void
1093 GNUNET_CRYPTO_ecdhe_key_get_public (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1094                                     struct GNUNET_CRYPTO_EcdhePublicKey *pub);
1095
1096
1097 /**
1098  * Convert a public key to a string.
1099  *
1100  * @param pub key to convert
1101  * @return string representing @a pub
1102  */
1103 char *
1104 GNUNET_CRYPTO_ecdsa_public_key_to_string (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1105
1106
1107 /**
1108  * Convert a private key to a string.
1109  *
1110  * @param priv key to convert
1111  * @return string representing @a pub
1112  */
1113 char *
1114 GNUNET_CRYPTO_eddsa_private_key_to_string (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv);
1115
1116
1117 /**
1118  * Convert a public key to a string.
1119  *
1120  * @param pub key to convert
1121  * @return string representing @a pub
1122  */
1123 char *
1124 GNUNET_CRYPTO_eddsa_public_key_to_string (const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1125
1126
1127 /**
1128  * Convert a string representing a public key to a public key.
1129  *
1130  * @param enc encoded public key
1131  * @param enclen number of bytes in @a enc (without 0-terminator)
1132  * @param pub where to store the public key
1133  * @return #GNUNET_OK on success
1134  */
1135 int
1136 GNUNET_CRYPTO_ecdsa_public_key_from_string (const char *enc,
1137                                             size_t enclen,
1138                                             struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1139
1140
1141 /**
1142  * Convert a string representing a private key to a private key.
1143  *
1144  * @param enc encoded public key
1145  * @param enclen number of bytes in @a enc (without 0-terminator)
1146  * @param priv where to store the private key
1147  * @return #GNUNET_OK on success
1148  */
1149 int
1150 GNUNET_CRYPTO_eddsa_private_key_from_string (const char *enc,
1151                                              size_t enclen,
1152                                              struct GNUNET_CRYPTO_EddsaPrivateKey *pub);
1153
1154
1155 /**
1156  * Convert a string representing a public key to a public key.
1157  *
1158  * @param enc encoded public key
1159  * @param enclen number of bytes in @a enc (without 0-terminator)
1160  * @param pub where to store the public key
1161  * @return #GNUNET_OK on success
1162  */
1163 int
1164 GNUNET_CRYPTO_eddsa_public_key_from_string (const char *enc,
1165                                             size_t enclen,
1166                                             struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1167
1168
1169 /**
1170  * @ingroup crypto
1171  * Create a new private key by reading it from a file.  If the
1172  * files does not exist, create a new key and write it to the
1173  * file.  Caller must free return value.  Note that this function
1174  * can not guarantee that another process might not be trying
1175  * the same operation on the same file at the same time.
1176  * If the contents of the file
1177  * are invalid the old file is deleted and a fresh key is
1178  * created.
1179  *
1180  * @param filename name of file to use to store the key
1181  * @return new private key, NULL on error (for example,
1182  *   permission denied); free using #GNUNET_free
1183  */
1184 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1185 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename);
1186
1187
1188 /**
1189  * @ingroup crypto
1190  * Create a new private key by reading it from a file.  If the
1191  * files does not exist, create a new key and write it to the
1192  * file.  Caller must free return value.  Note that this function
1193  * can not guarantee that another process might not be trying
1194  * the same operation on the same file at the same time.
1195  * If the contents of the file
1196  * are invalid the old file is deleted and a fresh key is
1197  * created.
1198  *
1199  * @param filename name of file to use to store the key
1200  * @return new private key, NULL on error (for example,
1201  *   permission denied); free using #GNUNET_free
1202  */
1203 struct GNUNET_CRYPTO_EddsaPrivateKey *
1204 GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename);
1205
1206
1207 /**
1208  * Forward declaration to simplify #include-structure.
1209  */
1210 struct GNUNET_CONFIGURATION_Handle;
1211
1212
1213 /**
1214  * @ingroup crypto
1215  * Create a new private key by reading our peer's key from
1216  * the file specified in the configuration.
1217  *
1218  * @param cfg the configuration to use
1219  * @return new private key, NULL on error (for example,
1220  *   permission denied); free using #GNUNET_free
1221  */
1222 struct GNUNET_CRYPTO_EddsaPrivateKey *
1223 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg);
1224
1225
1226 /**
1227  * @ingroup crypto
1228  * Create a new private key. Caller must free return value.
1229  *
1230  * @return fresh private key; free using #GNUNET_free
1231  */
1232 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1233 GNUNET_CRYPTO_ecdsa_key_create (void);
1234
1235
1236 /**
1237  * @ingroup crypto
1238  * Create a new private key. Caller must free return value.
1239  *
1240  * @return fresh private key; free using #GNUNET_free
1241  */
1242 struct GNUNET_CRYPTO_EddsaPrivateKey *
1243 GNUNET_CRYPTO_eddsa_key_create (void);
1244
1245
1246 /**
1247  * @ingroup crypto
1248  * Create a new private key.  Clear with #GNUNET_CRYPTO_ecdhe_key_clear().
1249  *
1250  * @param[out] pk set to fresh private key;
1251  * @return #GNUNET_OK on success, #GNUNET_SYSERR on failure
1252  */
1253 int
1254 GNUNET_CRYPTO_ecdhe_key_create2 (struct GNUNET_CRYPTO_EcdhePrivateKey *pk);
1255
1256
1257 /**
1258  * @ingroup crypto
1259  * Create a new private key. Caller must free return value.
1260  *
1261  * @return fresh private key; free using #GNUNET_free
1262  */
1263 struct GNUNET_CRYPTO_EcdhePrivateKey *
1264 GNUNET_CRYPTO_ecdhe_key_create (void);
1265
1266
1267 /**
1268  * @ingroup crypto
1269  * Clear memory that was used to store a private key.
1270  *
1271  * @param pk location of the key
1272  */
1273 void
1274 GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk);
1275
1276
1277 /**
1278  * @ingroup crypto
1279  * Clear memory that was used to store a private key.
1280  *
1281  * @param pk location of the key
1282  */
1283 void
1284 GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk);
1285
1286
1287 /**
1288  * @ingroup crypto
1289  * Clear memory that was used to store a private key.
1290  *
1291  * @param pk location of the key
1292  */
1293 void
1294 GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk);
1295
1296
1297 /**
1298  * @ingroup crypto
1299  * Get the shared private key we use for anonymous users.
1300  *
1301  * @return "anonymous" private key; do not free
1302  */
1303 const struct GNUNET_CRYPTO_EcdsaPrivateKey *
1304 GNUNET_CRYPTO_ecdsa_key_get_anonymous (void);
1305
1306
1307 /**
1308  * @ingroup crypto
1309  * Setup a hostkey file for a peer given the name of the
1310  * configuration file (!).  This function is used so that
1311  * at a later point code can be certain that reading a
1312  * hostkey is fast (for example in time-dependent testcases).
1313 *
1314  * @param cfg_name name of the configuration file to use
1315  */
1316 void
1317 GNUNET_CRYPTO_eddsa_setup_hostkey (const char *cfg_name);
1318
1319
1320 /**
1321  * @ingroup crypto
1322  * Retrieve the identity of the host's peer.
1323  *
1324  * @param cfg configuration to use
1325  * @param dst pointer to where to write the peer identity
1326  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
1327  *         could not be retrieved
1328  */
1329 int
1330 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
1331                                  struct GNUNET_PeerIdentity *dst);
1332
1333
1334 /**
1335  * Compare two Peer Identities.
1336  *
1337  * @param first first peer identity
1338  * @param second second peer identity
1339  * @return bigger than 0 if first > second,
1340  *         0 if they are the same
1341  *         smaller than 0 if second > first
1342  */
1343 int
1344 GNUNET_CRYPTO_cmp_peer_identity (const struct GNUNET_PeerIdentity *first,
1345                                  const struct GNUNET_PeerIdentity *second);
1346
1347
1348 /**
1349  * Internal structure used to cache pre-calculated values for DLOG calculation.
1350  */
1351 struct GNUNET_CRYPTO_EccDlogContext;
1352
1353
1354 /**
1355  * Point on a curve (always for Curve25519) encoded in a format suitable
1356  * for network transmission (ECDH), see http://cr.yp.to/ecdh.html.
1357  */
1358 struct GNUNET_CRYPTO_EccPoint
1359 {
1360   /**
1361    * Q consists of an x- and a y-value, each mod p (256 bits), given
1362    * here in affine coordinates and Ed25519 standard compact format.
1363    */
1364   unsigned char q_y[256 / 8];
1365 };
1366
1367
1368 /**
1369  * Do pre-calculation for ECC discrete logarithm for small factors.
1370  *
1371  * @param max maximum value the factor can be
1372  * @param mem memory to use (should be smaller than @a max), must not be zero.
1373  * @return NULL on error
1374  */
1375 struct GNUNET_CRYPTO_EccDlogContext *
1376 GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max,
1377                                 unsigned int mem);
1378
1379
1380 /**
1381  * Calculate ECC discrete logarithm for small factors.
1382  * Opposite of #GNUNET_CRYPTO_ecc_dexp().
1383  *
1384  * @param dlc precalculated values, determine range of factors
1385  * @param input point on the curve to factor
1386  * @return INT_MAX if dlog failed, otherwise the factor
1387  */
1388 int
1389 GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc,
1390                         gcry_mpi_point_t input);
1391
1392
1393 /**
1394  * Multiply the generator g of the elliptic curve by @a val
1395  * to obtain the point on the curve representing @a val.
1396  * Afterwards, point addition will correspond to integer
1397  * addition.  #GNUNET_CRYPTO_ecc_dlog() can be used to
1398  * convert a point back to an integer (as long as the
1399  * integer is smaller than the MAX of the @a edc context).
1400  *
1401  * @param edc calculation context for ECC operations
1402  * @param val value to encode into a point
1403  * @return representation of the value as an ECC point,
1404  *         must be freed using #GNUNET_CRYPTO_ecc_free()
1405  */
1406 gcry_mpi_point_t
1407 GNUNET_CRYPTO_ecc_dexp (struct GNUNET_CRYPTO_EccDlogContext *edc,
1408                         int val);
1409
1410
1411 /**
1412  * Multiply the generator g of the elliptic curve by @a val
1413  * to obtain the point on the curve representing @a val.
1414  *
1415  * @param edc calculation context for ECC operations
1416  * @param val (positive) value to encode into a point
1417  * @return representation of the value as an ECC point,
1418  *         must be freed using #GNUNET_CRYPTO_ecc_free()
1419  */
1420 gcry_mpi_point_t
1421 GNUNET_CRYPTO_ecc_dexp_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
1422                             gcry_mpi_t val);
1423
1424
1425 /**
1426  * Multiply the point @a p on the elliptic curve by @a val.
1427  *
1428  * @param edc calculation context for ECC operations
1429  * @param p point to multiply
1430  * @param val (positive) value to encode into a point
1431  * @return representation of the value as an ECC point,
1432  *         must be freed using #GNUNET_CRYPTO_ecc_free()
1433  */
1434 gcry_mpi_point_t
1435 GNUNET_CRYPTO_ecc_pmul_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
1436                             gcry_mpi_point_t p,
1437                             gcry_mpi_t val);
1438
1439
1440 /**
1441  * Convert point value to binary representation.
1442  *
1443  * @param edc calculation context for ECC operations
1444  * @param point computational point representation
1445  * @param[out] bin binary point representation
1446  */
1447 void
1448 GNUNET_CRYPTO_ecc_point_to_bin (struct GNUNET_CRYPTO_EccDlogContext *edc,
1449                                 gcry_mpi_point_t point,
1450                                 struct GNUNET_CRYPTO_EccPoint *bin);
1451
1452
1453 /**
1454  * Convert binary representation of a point to computational representation.
1455  *
1456  * @param edc calculation context for ECC operations
1457  * @param bin binary point representation
1458  * @return computational representation
1459  */
1460 gcry_mpi_point_t
1461 GNUNET_CRYPTO_ecc_bin_to_point (struct GNUNET_CRYPTO_EccDlogContext *edc,
1462                                 const struct GNUNET_CRYPTO_EccPoint *bin);
1463
1464
1465 /**
1466  * Add two points on the elliptic curve.
1467  *
1468  * @param edc calculation context for ECC operations
1469  * @param a some value
1470  * @param b some value
1471  * @return @a a + @a b, must be freed using #GNUNET_CRYPTO_ecc_free()
1472  */
1473 gcry_mpi_point_t
1474 GNUNET_CRYPTO_ecc_add (struct GNUNET_CRYPTO_EccDlogContext *edc,
1475                        gcry_mpi_point_t a,
1476                        gcry_mpi_point_t b);
1477
1478
1479 /**
1480  * Obtain a random point on the curve and its
1481  * additive inverse. Both returned values
1482  * must be freed using #GNUNET_CRYPTO_ecc_free().
1483  *
1484  * @param edc calculation context for ECC operations
1485  * @param[out] r set to a random point on the curve
1486  * @param[out] r_inv set to the additive inverse of @a r
1487  */
1488 void
1489 GNUNET_CRYPTO_ecc_rnd (struct GNUNET_CRYPTO_EccDlogContext *edc,
1490                        gcry_mpi_point_t *r,
1491                        gcry_mpi_point_t *r_inv);
1492
1493
1494 /**
1495  * Obtain a random scalar for point multiplication on the curve and
1496  * its multiplicative inverse.
1497  *
1498  * @param edc calculation context for ECC operations
1499  * @param[out] r set to a random scalar on the curve
1500  * @param[out] r_inv set to the multiplicative inverse of @a r
1501  */
1502 void
1503 GNUNET_CRYPTO_ecc_rnd_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
1504                            gcry_mpi_t *r,
1505                            gcry_mpi_t *r_inv);
1506
1507
1508 /**
1509  * Generate a random value mod n.
1510  *
1511  * @param edc ECC context
1512  * @return random value mod n.
1513  */
1514 gcry_mpi_t
1515 GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc);
1516
1517
1518 /**
1519  * Free a point value returned by the API.
1520  *
1521  * @param p point to free
1522  */
1523 void
1524 GNUNET_CRYPTO_ecc_free (gcry_mpi_point_t p);
1525
1526
1527 /**
1528  * Release precalculated values.
1529  *
1530  * @param dlc dlog context
1531  */
1532 void
1533 GNUNET_CRYPTO_ecc_dlog_release (struct GNUNET_CRYPTO_EccDlogContext *dlc);
1534
1535
1536 /**
1537  * @ingroup crypto
1538  * Derive key material from a public and a private ECC key.
1539  *
1540  * @param priv private key to use for the ECDH (x)
1541  * @param pub public key to use for the ECDH (yG)
1542  * @param key_material where to write the key material (xyG)
1543  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1544  */
1545 int
1546 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1547                         const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1548                         struct GNUNET_HashCode *key_material);
1549
1550
1551 /**
1552  * @ingroup crypto
1553  * Derive key material from a ECDH public key and a private EdDSA key.
1554  * Dual to #GNUNET_CRRYPTO_ecdh_eddsa.
1555  *
1556  * @param priv private key from EdDSA to use for the ECDH (x)
1557  * @param pub public key to use for the ECDH (yG)
1558  * @param key_material where to write the key material H(h(x)yG)
1559  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1560  */
1561 int
1562 GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1563                           const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1564                           struct GNUNET_HashCode *key_material);
1565
1566 /**
1567  * @ingroup crypto
1568  * Derive key material from a ECDH public key and a private ECDSA key.
1569  * Dual to #GNUNET_CRRYPTO_ecdh_ecdsa.
1570  *
1571  * @param priv private key from ECDSA to use for the ECDH (x)
1572  * @param pub public key to use for the ECDH (yG)
1573  * @param key_material where to write the key material H(h(x)yG)
1574  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1575  */
1576 int
1577 GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1578                           const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1579                           struct GNUNET_HashCode *key_material);
1580
1581
1582 /**
1583  * @ingroup crypto
1584  * Derive key material from a EdDSA public key and a private ECDH key.
1585  * Dual to #GNUNET_CRRYPTO_eddsa_ecdh.
1586  *
1587  * @param priv private key to use for the ECDH (y)
1588  * @param pub public key from EdDSA to use for the ECDH (X=h(x)G)
1589  * @param key_material where to write the key material H(yX)=H(h(x)yG)
1590  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1591  */
1592 int
1593 GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1594                           const struct GNUNET_CRYPTO_EddsaPublicKey *pub,
1595                           struct GNUNET_HashCode *key_material);
1596
1597 /**
1598  * @ingroup crypto
1599  * Derive key material from a EcDSA public key and a private ECDH key.
1600  * Dual to #GNUNET_CRRYPTO_ecdsa_ecdh.
1601  *
1602  * @param priv private key to use for the ECDH (y)
1603  * @param pub public key from ECDSA to use for the ECDH (X=h(x)G)
1604  * @param key_material where to write the key material H(yX)=H(h(x)yG)
1605  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1606  */
1607 int
1608 GNUNET_CRYPTO_ecdh_ecdsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1609                           const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1610                           struct GNUNET_HashCode *key_material);
1611
1612
1613 /**
1614  * @ingroup crypto
1615  * EdDSA sign a given block.
1616  *
1617  * @param priv private key to use for the signing
1618  * @param purpose what to sign (size, purpose)
1619  * @param sig where to write the signature
1620  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1621  */
1622 int
1623 GNUNET_CRYPTO_eddsa_sign (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1624                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1625                           struct GNUNET_CRYPTO_EddsaSignature *sig);
1626
1627
1628 /**
1629  * @ingroup crypto
1630  * ECDSA Sign a given block.
1631  *
1632  * @param priv private key to use for the signing
1633  * @param purpose what to sign (size, purpose)
1634  * @param sig where to write the signature
1635  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1636  */
1637 int
1638 GNUNET_CRYPTO_ecdsa_sign (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1639                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1640                           struct GNUNET_CRYPTO_EcdsaSignature *sig);
1641
1642 /**
1643  * @ingroup crypto
1644  * Verify EdDSA signature.
1645  *
1646  * @param purpose what is the purpose that the signature should have?
1647  * @param validate block to validate (size, purpose, data)
1648  * @param sig signature that is being validated
1649  * @param pub public key of the signer
1650  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1651  */
1652 int
1653 GNUNET_CRYPTO_eddsa_verify (uint32_t purpose,
1654                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1655                             const struct GNUNET_CRYPTO_EddsaSignature *sig,
1656                             const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1657
1658
1659
1660 /**
1661  * @ingroup crypto
1662  * Verify ECDSA signature.
1663  *
1664  * @param purpose what is the purpose that the signature should have?
1665  * @param validate block to validate (size, purpose, data)
1666  * @param sig signature that is being validated
1667  * @param pub public key of the signer
1668  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1669  */
1670 int
1671 GNUNET_CRYPTO_ecdsa_verify (uint32_t purpose,
1672                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1673                             const struct GNUNET_CRYPTO_EcdsaSignature *sig,
1674                             const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1675
1676
1677 /**
1678  * @ingroup crypto
1679  * Derive a private key from a given private key and a label.
1680  * Essentially calculates a private key 'h = H(l,P) * d mod n'
1681  * where n is the size of the ECC group and P is the public
1682  * key associated with the private key 'd'.
1683  *
1684  * @param priv original private key
1685  * @param label label to use for key deriviation
1686  * @param context additional context to use for HKDF of 'h';
1687  *        typically the name of the subsystem/application
1688  * @return derived private key
1689  */
1690 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1691 GNUNET_CRYPTO_ecdsa_private_key_derive (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1692                                         const char *label,
1693                                         const char *context);
1694
1695
1696 /**
1697  * @ingroup crypto
1698  * Derive a public key from a given public key and a label.
1699  * Essentially calculates a public key 'V = H(l,P) * P'.
1700  *
1701  * @param pub original public key
1702  * @param label label to use for key deriviation
1703  * @param context additional context to use for HKDF of 'h'.
1704  *        typically the name of the subsystem/application
1705  * @param result where to write the derived public key
1706  */
1707 void
1708 GNUNET_CRYPTO_ecdsa_public_key_derive (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1709                                        const char *label,
1710                                        const char *context,
1711                                        struct GNUNET_CRYPTO_EcdsaPublicKey *result);
1712
1713
1714 /**
1715  * Output the given MPI value to the given buffer in network
1716  * byte order.  The MPI @a val may not be negative.
1717  *
1718  * @param buf where to output to
1719  * @param size number of bytes in @a buf
1720  * @param val value to write to @a buf
1721  */
1722 void
1723 GNUNET_CRYPTO_mpi_print_unsigned (void *buf,
1724                                   size_t size,
1725                                   gcry_mpi_t val);
1726
1727
1728 /**
1729  * Convert data buffer into MPI value.
1730  * The buffer is interpreted as network
1731  * byte order, unsigned integer.
1732  *
1733  * @param result where to store MPI value (allocated)
1734  * @param data raw data (GCRYMPI_FMT_USG)
1735  * @param size number of bytes in @a data
1736  */
1737 void
1738 GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result,
1739                                  const void *data,
1740                                  size_t size);
1741
1742
1743 /**
1744  * Create a freshly generated paillier public key.
1745  *
1746  * @param[out] public_key Where to store the public key?
1747  * @param[out] private_key Where to store the private key?
1748  */
1749 void
1750 GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1751                                struct GNUNET_CRYPTO_PaillierPrivateKey *private_key);
1752
1753
1754 /**
1755  * Encrypt a plaintext with a paillier public key.
1756  *
1757  * @param public_key Public key to use.
1758  * @param m Plaintext to encrypt.
1759  * @param desired_ops How many homomorphic ops the caller intends to use
1760  * @param[out] ciphertext Encrytion of @a plaintext with @a public_key.
1761  * @return guaranteed number of supported homomorphic operations >= 1,
1762  *         or desired_ops, in case that is lower,
1763  *         or -1 if less than one homomorphic operation is possible
1764  */
1765 int
1766 GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1767                                 const gcry_mpi_t m,
1768                                 int desired_ops,
1769                                 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext);
1770
1771
1772 /**
1773  * Decrypt a paillier ciphertext with a private key.
1774  *
1775  * @param private_key Private key to use for decryption.
1776  * @param public_key Public key to use for decryption.
1777  * @param ciphertext Ciphertext to decrypt.
1778  * @param[out] m Decryption of @a ciphertext with @private_key.
1779  */
1780 void
1781 GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key,
1782                                 const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1783                                 const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext,
1784                                 gcry_mpi_t m);
1785
1786
1787 /**
1788  * Compute a ciphertext that represents the sum of the plaintext in @a x1 and @a x2
1789  *
1790  * Note that this operation can only be done a finite number of times
1791  * before an overflow occurs.
1792  *
1793  * @param public_key Public key to use for encryption.
1794  * @param c1 Paillier cipher text.
1795  * @param c2 Paillier cipher text.
1796  * @param[out] result Result of the homomorphic operation.
1797  * @return #GNUNET_OK if the result could be computed,
1798  *         #GNUNET_SYSERR if no more homomorphic operations are remaining.
1799  */
1800 int
1801 GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1802                                 const struct GNUNET_CRYPTO_PaillierCiphertext *c1,
1803                                 const struct GNUNET_CRYPTO_PaillierCiphertext *c2,
1804                                 struct GNUNET_CRYPTO_PaillierCiphertext *result);
1805
1806
1807 /**
1808  * Get the number of remaining supported homomorphic operations.
1809  *
1810  * @param c Paillier cipher text.
1811  * @return the number of remaining homomorphic operations
1812  */
1813 int
1814 GNUNET_CRYPTO_paillier_hom_get_remaining (const struct GNUNET_CRYPTO_PaillierCiphertext *c);
1815
1816
1817 /* ********* Chaum-style RSA-based blind signatures ******************* */
1818
1819
1820
1821
1822 /**
1823  * The private information of an RSA key pair.
1824  */
1825 struct GNUNET_CRYPTO_RsaPrivateKey;
1826
1827 /**
1828  * The public information of an RSA key pair.
1829  */
1830 struct GNUNET_CRYPTO_RsaPublicKey;
1831
1832 /**
1833  * Constant-size pre-secret for blinding key generation.
1834  */
1835 struct GNUNET_CRYPTO_RsaBlindingKeySecret
1836 {
1837   /**
1838    * Bits used to generate the blinding key.  256 bits
1839    * of entropy is enough.
1840    */
1841   uint32_t pre_secret[8] GNUNET_PACKED;
1842 };
1843
1844 /**
1845  * @brief an RSA signature
1846  */
1847 struct GNUNET_CRYPTO_RsaSignature;
1848
1849
1850 /**
1851  * Create a new private key. Caller must free return value.
1852  *
1853  * @param len length of the key in bits (i.e. 2048)
1854  * @return fresh private key
1855  */
1856 struct GNUNET_CRYPTO_RsaPrivateKey *
1857 GNUNET_CRYPTO_rsa_private_key_create (unsigned int len);
1858
1859
1860 /**
1861  * Free memory occupied by the private key.
1862  *
1863  * @param key pointer to the memory to free
1864  */
1865 void
1866 GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key);
1867
1868
1869 /**
1870  * Encode the private key in a format suitable for
1871  * storing it into a file.
1872  *
1873  * @param key the private key
1874  * @param[out] buffer set to a buffer with the encoded key
1875  * @return size of memory allocatedin @a buffer
1876  */
1877 size_t
1878 GNUNET_CRYPTO_rsa_private_key_encode (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1879                                       char **buffer);
1880
1881
1882 /**
1883  * Decode the private key from the data-format back
1884  * to the "normal", internal format.
1885  *
1886  * @param buf the buffer where the private key data is stored
1887  * @param len the length of the data in @a buf
1888  * @return NULL on error
1889  */
1890 struct GNUNET_CRYPTO_RsaPrivateKey *
1891 GNUNET_CRYPTO_rsa_private_key_decode (const char *buf,
1892                                       size_t len);
1893
1894
1895 /**
1896  * Duplicate the given private key
1897  *
1898  * @param key the private key to duplicate
1899  * @return the duplicate key; NULL upon error
1900  */
1901 struct GNUNET_CRYPTO_RsaPrivateKey *
1902 GNUNET_CRYPTO_rsa_private_key_dup (const struct GNUNET_CRYPTO_RsaPrivateKey *key);
1903
1904
1905 /**
1906  * Extract the public key of the given private key.
1907  *
1908  * @param priv the private key
1909  * @retur NULL on error, otherwise the public key
1910  */
1911 struct GNUNET_CRYPTO_RsaPublicKey *
1912 GNUNET_CRYPTO_rsa_private_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey *priv);
1913
1914
1915 /**
1916  * Compute hash over the public key.
1917  *
1918  * @param key public key to hash
1919  * @param hc where to store the hash code
1920  */
1921 void
1922 GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key,
1923                                    struct GNUNET_HashCode *hc);
1924
1925
1926 /**
1927  * Obtain the length of the RSA key in bits.
1928  *
1929  * @param key the public key to introspect
1930  * @return length of the key in bits
1931  */
1932 unsigned int
1933 GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key);
1934
1935
1936 /**
1937  * Free memory occupied by the public key.
1938  *
1939  * @param key pointer to the memory to free
1940  */
1941 void
1942 GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key);
1943
1944
1945 /**
1946  * Encode the public key in a format suitable for
1947  * storing it into a file.
1948  *
1949  * @param key the private key
1950  * @param[out] buffer set to a buffer with the encoded key
1951  * @return size of memory allocated in @a buffer
1952  */
1953 size_t
1954 GNUNET_CRYPTO_rsa_public_key_encode (const struct GNUNET_CRYPTO_RsaPublicKey *key,
1955                                      char **buffer);
1956
1957
1958 /**
1959  * Decode the public key from the data-format back
1960  * to the "normal", internal format.
1961  *
1962  * @param buf the buffer where the public key data is stored
1963  * @param len the length of the data in @a buf
1964  * @return NULL on error
1965  */
1966 struct GNUNET_CRYPTO_RsaPublicKey *
1967 GNUNET_CRYPTO_rsa_public_key_decode (const char *buf,
1968                                      size_t len);
1969
1970
1971 /**
1972  * Duplicate the given public key
1973  *
1974  * @param key the public key to duplicate
1975  * @return the duplicate key; NULL upon error
1976  */
1977 struct GNUNET_CRYPTO_RsaPublicKey *
1978 GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key);
1979
1980
1981 /**
1982  * Compare the values of two signatures.
1983  *
1984  * @param s1 one signature
1985  * @param s2 the other signature
1986  * @return 0 if the two are equal
1987  */
1988 int
1989 GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1,
1990                                  struct GNUNET_CRYPTO_RsaSignature *s2);
1991
1992 /**
1993  * Compare the values of two private keys.
1994  *
1995  * @param p1 one private key
1996  * @param p2 the other private key
1997  * @return 0 if the two are equal
1998  */
1999 int
2000 GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1,
2001                                   struct GNUNET_CRYPTO_RsaPrivateKey *p2);
2002
2003
2004 /**
2005  * Compare the values of two public keys.
2006  *
2007  * @param p1 one public key
2008  * @param p2 the other public key
2009  * @return 0 if the two are equal
2010  */
2011 int
2012 GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1,
2013                                   struct GNUNET_CRYPTO_RsaPublicKey *p2);
2014
2015
2016 /**
2017  * Blinds the given message with the given blinding key
2018  *
2019  * @param hash hash of the message to sign
2020  * @param bkey the blinding key
2021  * @param pkey the public key of the signer
2022  * @param[out] buf set to a buffer with the blinded message to be signed
2023  * @param[out] buf_size number of bytes stored in @a buf
2024  * @return #GNUNET_YES if successful, #GNUNET_NO if RSA key is malicious
2025  */
2026 int
2027 GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash,
2028                          const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks,
2029                          struct GNUNET_CRYPTO_RsaPublicKey *pkey,
2030                          char **buf,
2031                          size_t *buf_size);
2032
2033
2034 /**
2035  * Sign a blinded value, which must be a full domain hash of a message.
2036  *
2037  * @param key private key to use for the signing
2038  * @param msg the (blinded) message to sign
2039  * @param msg_len number of bytes in @a msg to sign
2040  * @return NULL on error, signature on success
2041  */
2042 struct GNUNET_CRYPTO_RsaSignature *
2043 GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
2044                                 const void *msg,
2045                                 size_t msg_len);
2046
2047
2048 /**
2049  * Create and sign a full domain hash of a message.
2050  *
2051  * @param key private key to use for the signing
2052  * @param hash the hash of the message to sign
2053  * @return NULL on error, including a malicious RSA key, signature on success
2054  */
2055 struct GNUNET_CRYPTO_RsaSignature *
2056 GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
2057                             const struct GNUNET_HashCode *hash);
2058
2059
2060 /**
2061  * Free memory occupied by signature.
2062  *
2063  * @param sig memory to free
2064  */
2065 void
2066 GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig);
2067
2068
2069 /**
2070  * Encode the given signature in a format suitable for storing it into a file.
2071  *
2072  * @param sig the signature
2073  * @param[out] buffer set to a buffer with the encoded key
2074  * @return size of memory allocated in @a buffer
2075  */
2076 size_t
2077 GNUNET_CRYPTO_rsa_signature_encode (const struct GNUNET_CRYPTO_RsaSignature *sig,
2078                                     char **buffer);
2079
2080
2081 /**
2082  * Decode the signature from the data-format back to the "normal", internal
2083  * format.
2084  *
2085  * @param buf the buffer where the public key data is stored
2086  * @param len the length of the data in @a buf
2087  * @return NULL on error
2088  */
2089 struct GNUNET_CRYPTO_RsaSignature *
2090 GNUNET_CRYPTO_rsa_signature_decode (const char *buf,
2091                                     size_t len);
2092
2093
2094 /**
2095  * Duplicate the given rsa signature
2096  *
2097  * @param sig the signature to duplicate
2098  * @return the duplicate key; NULL upon error
2099  */
2100 struct GNUNET_CRYPTO_RsaSignature *
2101 GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig);
2102
2103
2104 /**
2105  * Unblind a blind-signed signature.  The signature should have been generated
2106  * with #GNUNET_CRYPTO_rsa_sign() using a hash that was blinded with
2107  * #GNUNET_CRYPTO_rsa_blind().
2108  *
2109  * @param sig the signature made on the blinded signature purpose
2110  * @param bks the blinding key secret used to blind the signature purpose
2111  * @param pkey the public key of the signer
2112  * @return unblinded signature on success, NULL if RSA key is bad or malicious.
2113  */
2114 struct GNUNET_CRYPTO_RsaSignature *
2115 GNUNET_CRYPTO_rsa_unblind (const struct GNUNET_CRYPTO_RsaSignature *sig,
2116                            const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks,
2117                            struct GNUNET_CRYPTO_RsaPublicKey *pkey);
2118
2119
2120 /**
2121  * Verify whether the given hash corresponds to the given signature and the
2122  * signature is valid with respect to the given public key.
2123  *
2124  * @param hash the message to verify to match the @a sig
2125  * @param sig signature that is being validated
2126  * @param public_key public key of the signer
2127  * @returns #GNUNET_YES if ok, #GNUNET_NO if RSA key is malicious, #GNUNET_SYSERR if signature
2128  */
2129 int
2130 GNUNET_CRYPTO_rsa_verify (const struct GNUNET_HashCode *hash,
2131                           const struct GNUNET_CRYPTO_RsaSignature *sig,
2132                           const struct GNUNET_CRYPTO_RsaPublicKey *public_key);
2133
2134
2135 #if 0                           /* keep Emacsens' auto-indent happy */
2136 {
2137 #endif
2138 #ifdef __cplusplus
2139 }
2140 #endif
2141
2142
2143 /* ifndef GNUNET_CRYPTO_LIB_H */
2144 #endif
2145 /* end of gnunet_crypto_lib.h */