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