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