Implement data ack in CADET MQ API
[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 public key to a string.
1114  *
1115  * @param pub key to convert
1116  * @return string representing @a pub
1117  */
1118 char *
1119 GNUNET_CRYPTO_eddsa_public_key_to_string (const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1120
1121
1122 /**
1123  * Convert a string representing a public key to a public key.
1124  *
1125  * @param enc encoded public key
1126  * @param enclen number of bytes in @a enc (without 0-terminator)
1127  * @param pub where to store the public key
1128  * @return #GNUNET_OK on success
1129  */
1130 int
1131 GNUNET_CRYPTO_ecdsa_public_key_from_string (const char *enc,
1132                                             size_t enclen,
1133                                             struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1134
1135
1136 /**
1137  * Convert a string representing a private key to a private key.
1138  *
1139  * @param enc encoded public key
1140  * @param enclen number of bytes in @a enc (without 0-terminator)
1141  * @param priv where to store the private key
1142  * @return #GNUNET_OK on success
1143  */
1144 int
1145 GNUNET_CRYPTO_eddsa_private_key_from_string (const char *enc,
1146                                              size_t enclen,
1147                                              struct GNUNET_CRYPTO_EddsaPrivateKey *pub);
1148
1149
1150 /**
1151  * Convert a string representing a public key to a public key.
1152  *
1153  * @param enc encoded public key
1154  * @param enclen number of bytes in @a enc (without 0-terminator)
1155  * @param pub where to store the public key
1156  * @return #GNUNET_OK on success
1157  */
1158 int
1159 GNUNET_CRYPTO_eddsa_public_key_from_string (const char *enc,
1160                                             size_t enclen,
1161                                             struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1162
1163
1164 /**
1165  * @ingroup crypto
1166  * Create a new private key by reading it from a file.  If the
1167  * files does not exist, create a new key and write it to the
1168  * file.  Caller must free return value.  Note that this function
1169  * can not guarantee that another process might not be trying
1170  * the same operation on the same file at the same time.
1171  * If the contents of the file
1172  * are invalid the old file is deleted and a fresh key is
1173  * created.
1174  *
1175  * @param filename name of file to use to store the key
1176  * @return new private key, NULL on error (for example,
1177  *   permission denied); free using #GNUNET_free
1178  */
1179 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1180 GNUNET_CRYPTO_ecdsa_key_create_from_file (const char *filename);
1181
1182
1183 /**
1184  * @ingroup crypto
1185  * Create a new private key by reading it from a file.  If the
1186  * files does not exist, create a new key and write it to the
1187  * file.  Caller must free return value.  Note that this function
1188  * can not guarantee that another process might not be trying
1189  * the same operation on the same file at the same time.
1190  * If the contents of the file
1191  * are invalid the old file is deleted and a fresh key is
1192  * created.
1193  *
1194  * @param filename name of file to use to store the key
1195  * @return new private key, NULL on error (for example,
1196  *   permission denied); free using #GNUNET_free
1197  */
1198 struct GNUNET_CRYPTO_EddsaPrivateKey *
1199 GNUNET_CRYPTO_eddsa_key_create_from_file (const char *filename);
1200
1201
1202 /**
1203  * Forward declaration to simplify #include-structure.
1204  */
1205 struct GNUNET_CONFIGURATION_Handle;
1206
1207
1208 /**
1209  * @ingroup crypto
1210  * Create a new private key by reading our peer's key from
1211  * the file specified in the configuration.
1212  *
1213  * @param cfg the configuration to use
1214  * @return new private key, NULL on error (for example,
1215  *   permission denied); free using #GNUNET_free
1216  */
1217 struct GNUNET_CRYPTO_EddsaPrivateKey *
1218 GNUNET_CRYPTO_eddsa_key_create_from_configuration (const struct GNUNET_CONFIGURATION_Handle *cfg);
1219
1220
1221 /**
1222  * @ingroup crypto
1223  * Create a new private key. Caller must free return value.
1224  *
1225  * @return fresh private key; free using #GNUNET_free
1226  */
1227 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1228 GNUNET_CRYPTO_ecdsa_key_create (void);
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_EddsaPrivateKey *
1238 GNUNET_CRYPTO_eddsa_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_EcdhePrivateKey *
1248 GNUNET_CRYPTO_ecdhe_key_create (void);
1249
1250
1251 /**
1252  * @ingroup crypto
1253  * Clear memory that was used to store a private key.
1254  *
1255  * @param pk location of the key
1256  */
1257 void
1258 GNUNET_CRYPTO_eddsa_key_clear (struct GNUNET_CRYPTO_EddsaPrivateKey *pk);
1259
1260
1261 /**
1262  * @ingroup crypto
1263  * Clear memory that was used to store a private key.
1264  *
1265  * @param pk location of the key
1266  */
1267 void
1268 GNUNET_CRYPTO_ecdsa_key_clear (struct GNUNET_CRYPTO_EcdsaPrivateKey *pk);
1269
1270
1271 /**
1272  * @ingroup crypto
1273  * Clear memory that was used to store a private key.
1274  *
1275  * @param pk location of the key
1276  */
1277 void
1278 GNUNET_CRYPTO_ecdhe_key_clear (struct GNUNET_CRYPTO_EcdhePrivateKey *pk);
1279
1280
1281 /**
1282  * @ingroup crypto
1283  * Get the shared private key we use for anonymous users.
1284  *
1285  * @return "anonymous" private key; do not free
1286  */
1287 const struct GNUNET_CRYPTO_EcdsaPrivateKey *
1288 GNUNET_CRYPTO_ecdsa_key_get_anonymous (void);
1289
1290
1291 /**
1292  * @ingroup crypto
1293  * Setup a hostkey file for a peer given the name of the
1294  * configuration file (!).  This function is used so that
1295  * at a later point code can be certain that reading a
1296  * hostkey is fast (for example in time-dependent testcases).
1297 *
1298  * @param cfg_name name of the configuration file to use
1299  */
1300 void
1301 GNUNET_CRYPTO_eddsa_setup_hostkey (const char *cfg_name);
1302
1303
1304 /**
1305  * @ingroup crypto
1306  * Retrieve the identity of the host's peer.
1307  *
1308  * @param cfg configuration to use
1309  * @param dst pointer to where to write the peer identity
1310  * @return #GNUNET_OK on success, #GNUNET_SYSERR if the identity
1311  *         could not be retrieved
1312  */
1313 int
1314 GNUNET_CRYPTO_get_peer_identity (const struct GNUNET_CONFIGURATION_Handle *cfg,
1315                                  struct GNUNET_PeerIdentity *dst);
1316
1317
1318 /**
1319  * Compare two Peer Identities.
1320  *
1321  * @param first first peer identity
1322  * @param second second peer identity
1323  * @return bigger than 0 if first > second,
1324  *         0 if they are the same
1325  *         smaller than 0 if second > first
1326  */
1327 int
1328 GNUNET_CRYPTO_cmp_peer_identity (const struct GNUNET_PeerIdentity *first,
1329                                  const struct GNUNET_PeerIdentity *second);
1330
1331
1332 /**
1333  * Internal structure used to cache pre-calculated values for DLOG calculation.
1334  */
1335 struct GNUNET_CRYPTO_EccDlogContext;
1336
1337
1338 /**
1339  * Point on a curve (always for Curve25519) encoded in a format suitable
1340  * for network transmission (ECDH), see http://cr.yp.to/ecdh.html.
1341  */
1342 struct GNUNET_CRYPTO_EccPoint
1343 {
1344   /**
1345    * Q consists of an x- and a y-value, each mod p (256 bits), given
1346    * here in affine coordinates and Ed25519 standard compact format.
1347    */
1348   unsigned char q_y[256 / 8];
1349 };
1350
1351
1352 /**
1353  * Do pre-calculation for ECC discrete logarithm for small factors.
1354  *
1355  * @param max maximum value the factor can be
1356  * @param mem memory to use (should be smaller than @a max), must not be zero.
1357  * @return NULL on error
1358  */
1359 struct GNUNET_CRYPTO_EccDlogContext *
1360 GNUNET_CRYPTO_ecc_dlog_prepare (unsigned int max,
1361                                 unsigned int mem);
1362
1363
1364 /**
1365  * Calculate ECC discrete logarithm for small factors.
1366  * Opposite of #GNUNET_CRYPTO_ecc_dexp().
1367  *
1368  * @param dlc precalculated values, determine range of factors
1369  * @param input point on the curve to factor
1370  * @return INT_MAX if dlog failed, otherwise the factor
1371  */
1372 int
1373 GNUNET_CRYPTO_ecc_dlog (struct GNUNET_CRYPTO_EccDlogContext *edc,
1374                         gcry_mpi_point_t input);
1375
1376
1377 /**
1378  * Multiply the generator g of the elliptic curve by @a val
1379  * to obtain the point on the curve representing @a val.
1380  * Afterwards, point addition will correspond to integer
1381  * addition.  #GNUNET_CRYPTO_ecc_dlog() can be used to
1382  * convert a point back to an integer (as long as the
1383  * integer is smaller than the MAX of the @a edc context).
1384  *
1385  * @param edc calculation context for ECC operations
1386  * @param val value to encode into a point
1387  * @return representation of the value as an ECC point,
1388  *         must be freed using #GNUNET_CRYPTO_ecc_free()
1389  */
1390 gcry_mpi_point_t
1391 GNUNET_CRYPTO_ecc_dexp (struct GNUNET_CRYPTO_EccDlogContext *edc,
1392                         int val);
1393
1394
1395 /**
1396  * Multiply the generator g of the elliptic curve by @a val
1397  * to obtain the point on the curve representing @a val.
1398  *
1399  * @param edc calculation context for ECC operations
1400  * @param val (positive) value to encode into a point
1401  * @return representation of the value as an ECC point,
1402  *         must be freed using #GNUNET_CRYPTO_ecc_free()
1403  */
1404 gcry_mpi_point_t
1405 GNUNET_CRYPTO_ecc_dexp_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
1406                             gcry_mpi_t val);
1407
1408
1409 /**
1410  * Multiply the point @a p on the elliptic curve by @a val.
1411  *
1412  * @param edc calculation context for ECC operations
1413  * @param p point to multiply
1414  * @param val (positive) value to encode into a point
1415  * @return representation of the value as an ECC point,
1416  *         must be freed using #GNUNET_CRYPTO_ecc_free()
1417  */
1418 gcry_mpi_point_t
1419 GNUNET_CRYPTO_ecc_pmul_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
1420                             gcry_mpi_point_t p,
1421                             gcry_mpi_t val);
1422
1423
1424 /**
1425  * Convert point value to binary representation.
1426  *
1427  * @param edc calculation context for ECC operations
1428  * @param point computational point representation
1429  * @param[out] bin binary point representation
1430  */
1431 void
1432 GNUNET_CRYPTO_ecc_point_to_bin (struct GNUNET_CRYPTO_EccDlogContext *edc,
1433                                 gcry_mpi_point_t point,
1434                                 struct GNUNET_CRYPTO_EccPoint *bin);
1435
1436
1437 /**
1438  * Convert binary representation of a point to computational representation.
1439  *
1440  * @param edc calculation context for ECC operations
1441  * @param bin binary point representation
1442  * @return computational representation
1443  */
1444 gcry_mpi_point_t
1445 GNUNET_CRYPTO_ecc_bin_to_point (struct GNUNET_CRYPTO_EccDlogContext *edc,
1446                                 const struct GNUNET_CRYPTO_EccPoint *bin);
1447
1448
1449 /**
1450  * Add two points on the elliptic curve.
1451  *
1452  * @param edc calculation context for ECC operations
1453  * @param a some value
1454  * @param b some value
1455  * @return @a a + @a b, must be freed using #GNUNET_CRYPTO_ecc_free()
1456  */
1457 gcry_mpi_point_t
1458 GNUNET_CRYPTO_ecc_add (struct GNUNET_CRYPTO_EccDlogContext *edc,
1459                        gcry_mpi_point_t a,
1460                        gcry_mpi_point_t b);
1461
1462
1463 /**
1464  * Obtain a random point on the curve and its
1465  * additive inverse. Both returned values
1466  * must be freed using #GNUNET_CRYPTO_ecc_free().
1467  *
1468  * @param edc calculation context for ECC operations
1469  * @param[out] r set to a random point on the curve
1470  * @param[out] r_inv set to the additive inverse of @a r
1471  */
1472 void
1473 GNUNET_CRYPTO_ecc_rnd (struct GNUNET_CRYPTO_EccDlogContext *edc,
1474                        gcry_mpi_point_t *r,
1475                        gcry_mpi_point_t *r_inv);
1476
1477
1478 /**
1479  * Obtain a random scalar for point multiplication on the curve and
1480  * its multiplicative inverse.
1481  *
1482  * @param edc calculation context for ECC operations
1483  * @param[out] r set to a random scalar on the curve
1484  * @param[out] r_inv set to the multiplicative inverse of @a r
1485  */
1486 void
1487 GNUNET_CRYPTO_ecc_rnd_mpi (struct GNUNET_CRYPTO_EccDlogContext *edc,
1488                            gcry_mpi_t *r,
1489                            gcry_mpi_t *r_inv);
1490
1491
1492 /**
1493  * Generate a random value mod n.
1494  *
1495  * @param edc ECC context
1496  * @return random value mod n.
1497  */
1498 gcry_mpi_t
1499 GNUNET_CRYPTO_ecc_random_mod_n (struct GNUNET_CRYPTO_EccDlogContext *edc);
1500
1501
1502 /**
1503  * Free a point value returned by the API.
1504  *
1505  * @param p point to free
1506  */
1507 void
1508 GNUNET_CRYPTO_ecc_free (gcry_mpi_point_t p);
1509
1510
1511 /**
1512  * Release precalculated values.
1513  *
1514  * @param dlc dlog context
1515  */
1516 void
1517 GNUNET_CRYPTO_ecc_dlog_release (struct GNUNET_CRYPTO_EccDlogContext *dlc);
1518
1519
1520 /**
1521  * @ingroup crypto
1522  * Derive key material from a public and a private ECC key.
1523  *
1524  * @param priv private key to use for the ECDH (x)
1525  * @param pub public key to use for the ECDH (yG)
1526  * @param key_material where to write the key material (xyG)
1527  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1528  */
1529 int
1530 GNUNET_CRYPTO_ecc_ecdh (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1531                         const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1532                         struct GNUNET_HashCode *key_material);
1533
1534
1535 /**
1536  * @ingroup crypto
1537  * Derive key material from a ECDH public key and a private EdDSA key.
1538  * Dual to #GNUNET_CRRYPTO_ecdh_eddsa.
1539  *
1540  * @param priv private key from EdDSA to use for the ECDH (x)
1541  * @param pub public key to use for the ECDH (yG)
1542  * @param key_material where to write the key material H(h(x)yG)
1543  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1544  */
1545 int
1546 GNUNET_CRYPTO_eddsa_ecdh (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1547                           const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1548                           struct GNUNET_HashCode *key_material);
1549
1550 /**
1551  * @ingroup crypto
1552  * Derive key material from a ECDH public key and a private ECDSA key.
1553  * Dual to #GNUNET_CRRYPTO_ecdh_ecdsa.
1554  *
1555  * @param priv private key from ECDSA to use for the ECDH (x)
1556  * @param pub public key to use for the ECDH (yG)
1557  * @param key_material where to write the key material H(h(x)yG)
1558  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1559  */
1560 int
1561 GNUNET_CRYPTO_ecdsa_ecdh (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1562                           const struct GNUNET_CRYPTO_EcdhePublicKey *pub,
1563                           struct GNUNET_HashCode *key_material);
1564
1565
1566 /**
1567  * @ingroup crypto
1568  * Derive key material from a EdDSA public key and a private ECDH key.
1569  * Dual to #GNUNET_CRRYPTO_eddsa_ecdh.
1570  *
1571  * @param priv private key to use for the ECDH (y)
1572  * @param pub public key from EdDSA to use for the ECDH (X=h(x)G)
1573  * @param key_material where to write the key material H(yX)=H(h(x)yG)
1574  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1575  */
1576 int
1577 GNUNET_CRYPTO_ecdh_eddsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1578                           const struct GNUNET_CRYPTO_EddsaPublicKey *pub,
1579                           struct GNUNET_HashCode *key_material);
1580
1581 /**
1582  * @ingroup crypto
1583  * Derive key material from a EcDSA public key and a private ECDH key.
1584  * Dual to #GNUNET_CRRYPTO_ecdsa_ecdh.
1585  *
1586  * @param priv private key to use for the ECDH (y)
1587  * @param pub public key from ECDSA to use for the ECDH (X=h(x)G)
1588  * @param key_material where to write the key material H(yX)=H(h(x)yG)
1589  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1590  */
1591 int
1592 GNUNET_CRYPTO_ecdh_ecdsa (const struct GNUNET_CRYPTO_EcdhePrivateKey *priv,
1593                           const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1594                           struct GNUNET_HashCode *key_material);
1595
1596
1597 /**
1598  * @ingroup crypto
1599  * EdDSA sign a given block.
1600  *
1601  * @param priv private key to use for the signing
1602  * @param purpose what to sign (size, purpose)
1603  * @param sig where to write the signature
1604  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1605  */
1606 int
1607 GNUNET_CRYPTO_eddsa_sign (const struct GNUNET_CRYPTO_EddsaPrivateKey *priv,
1608                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1609                           struct GNUNET_CRYPTO_EddsaSignature *sig);
1610
1611
1612 /**
1613  * @ingroup crypto
1614  * ECDSA Sign a given block.
1615  *
1616  * @param priv private key to use for the signing
1617  * @param purpose what to sign (size, purpose)
1618  * @param sig where to write the signature
1619  * @return #GNUNET_SYSERR on error, #GNUNET_OK on success
1620  */
1621 int
1622 GNUNET_CRYPTO_ecdsa_sign (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1623                           const struct GNUNET_CRYPTO_EccSignaturePurpose *purpose,
1624                           struct GNUNET_CRYPTO_EcdsaSignature *sig);
1625
1626 /**
1627  * @ingroup crypto
1628  * Verify EdDSA signature.
1629  *
1630  * @param purpose what is the purpose that the signature should have?
1631  * @param validate block to validate (size, purpose, data)
1632  * @param sig signature that is being validated
1633  * @param pub public key of the signer
1634  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1635  */
1636 int
1637 GNUNET_CRYPTO_eddsa_verify (uint32_t purpose,
1638                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1639                             const struct GNUNET_CRYPTO_EddsaSignature *sig,
1640                             const struct GNUNET_CRYPTO_EddsaPublicKey *pub);
1641
1642
1643
1644 /**
1645  * @ingroup crypto
1646  * Verify ECDSA signature.
1647  *
1648  * @param purpose what is the purpose that the signature should have?
1649  * @param validate block to validate (size, purpose, data)
1650  * @param sig signature that is being validated
1651  * @param pub public key of the signer
1652  * @returns #GNUNET_OK if ok, #GNUNET_SYSERR if invalid
1653  */
1654 int
1655 GNUNET_CRYPTO_ecdsa_verify (uint32_t purpose,
1656                             const struct GNUNET_CRYPTO_EccSignaturePurpose *validate,
1657                             const struct GNUNET_CRYPTO_EcdsaSignature *sig,
1658                             const struct GNUNET_CRYPTO_EcdsaPublicKey *pub);
1659
1660
1661 /**
1662  * @ingroup crypto
1663  * Derive a private key from a given private key and a label.
1664  * Essentially calculates a private key 'h = H(l,P) * d mod n'
1665  * where n is the size of the ECC group and P is the public
1666  * key associated with the private key 'd'.
1667  *
1668  * @param priv original private key
1669  * @param label label to use for key deriviation
1670  * @param context additional context to use for HKDF of 'h';
1671  *        typically the name of the subsystem/application
1672  * @return derived private key
1673  */
1674 struct GNUNET_CRYPTO_EcdsaPrivateKey *
1675 GNUNET_CRYPTO_ecdsa_private_key_derive (const struct GNUNET_CRYPTO_EcdsaPrivateKey *priv,
1676                                         const char *label,
1677                                         const char *context);
1678
1679
1680 /**
1681  * @ingroup crypto
1682  * Derive a public key from a given public key and a label.
1683  * Essentially calculates a public key 'V = H(l,P) * P'.
1684  *
1685  * @param pub original public key
1686  * @param label label to use for key deriviation
1687  * @param context additional context to use for HKDF of 'h'.
1688  *        typically the name of the subsystem/application
1689  * @param result where to write the derived public key
1690  */
1691 void
1692 GNUNET_CRYPTO_ecdsa_public_key_derive (const struct GNUNET_CRYPTO_EcdsaPublicKey *pub,
1693                                        const char *label,
1694                                        const char *context,
1695                                        struct GNUNET_CRYPTO_EcdsaPublicKey *result);
1696
1697
1698 /**
1699  * Output the given MPI value to the given buffer in network
1700  * byte order.  The MPI @a val may not be negative.
1701  *
1702  * @param buf where to output to
1703  * @param size number of bytes in @a buf
1704  * @param val value to write to @a buf
1705  */
1706 void
1707 GNUNET_CRYPTO_mpi_print_unsigned (void *buf,
1708                                   size_t size,
1709                                   gcry_mpi_t val);
1710
1711
1712 /**
1713  * Convert data buffer into MPI value.
1714  * The buffer is interpreted as network
1715  * byte order, unsigned integer.
1716  *
1717  * @param result where to store MPI value (allocated)
1718  * @param data raw data (GCRYMPI_FMT_USG)
1719  * @param size number of bytes in @a data
1720  */
1721 void
1722 GNUNET_CRYPTO_mpi_scan_unsigned (gcry_mpi_t *result,
1723                                  const void *data,
1724                                  size_t size);
1725
1726
1727 /**
1728  * Create a freshly generated paillier public key.
1729  *
1730  * @param[out] public_key Where to store the public key?
1731  * @param[out] private_key Where to store the private key?
1732  */
1733 void
1734 GNUNET_CRYPTO_paillier_create (struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1735                                struct GNUNET_CRYPTO_PaillierPrivateKey *private_key);
1736
1737
1738 /**
1739  * Encrypt a plaintext with a paillier public key.
1740  *
1741  * @param public_key Public key to use.
1742  * @param m Plaintext to encrypt.
1743  * @param desired_ops How many homomorphic ops the caller intends to use
1744  * @param[out] ciphertext Encrytion of @a plaintext with @a public_key.
1745  * @return guaranteed number of supported homomorphic operations >= 1,
1746  *         or desired_ops, in case that is lower,
1747  *         or -1 if less than one homomorphic operation is possible
1748  */
1749 int
1750 GNUNET_CRYPTO_paillier_encrypt (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1751                                 const gcry_mpi_t m,
1752                                 int desired_ops,
1753                                 struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext);
1754
1755
1756 /**
1757  * Decrypt a paillier ciphertext with a private key.
1758  *
1759  * @param private_key Private key to use for decryption.
1760  * @param public_key Public key to use for decryption.
1761  * @param ciphertext Ciphertext to decrypt.
1762  * @param[out] m Decryption of @a ciphertext with @private_key.
1763  */
1764 void
1765 GNUNET_CRYPTO_paillier_decrypt (const struct GNUNET_CRYPTO_PaillierPrivateKey *private_key,
1766                                 const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1767                                 const struct GNUNET_CRYPTO_PaillierCiphertext *ciphertext,
1768                                 gcry_mpi_t m);
1769
1770
1771 /**
1772  * Compute a ciphertext that represents the sum of the plaintext in @a x1 and @a x2
1773  *
1774  * Note that this operation can only be done a finite number of times
1775  * before an overflow occurs.
1776  *
1777  * @param public_key Public key to use for encryption.
1778  * @param c1 Paillier cipher text.
1779  * @param c2 Paillier cipher text.
1780  * @param[out] result Result of the homomorphic operation.
1781  * @return #GNUNET_OK if the result could be computed,
1782  *         #GNUNET_SYSERR if no more homomorphic operations are remaining.
1783  */
1784 int
1785 GNUNET_CRYPTO_paillier_hom_add (const struct GNUNET_CRYPTO_PaillierPublicKey *public_key,
1786                                 const struct GNUNET_CRYPTO_PaillierCiphertext *c1,
1787                                 const struct GNUNET_CRYPTO_PaillierCiphertext *c2,
1788                                 struct GNUNET_CRYPTO_PaillierCiphertext *result);
1789
1790
1791 /**
1792  * Get the number of remaining supported homomorphic operations.
1793  *
1794  * @param c Paillier cipher text.
1795  * @return the number of remaining homomorphic operations
1796  */
1797 int
1798 GNUNET_CRYPTO_paillier_hom_get_remaining (const struct GNUNET_CRYPTO_PaillierCiphertext *c);
1799
1800
1801 /* ********* Chaum-style RSA-based blind signatures ******************* */
1802
1803
1804
1805
1806 /**
1807  * The private information of an RSA key pair.
1808  */
1809 struct GNUNET_CRYPTO_RsaPrivateKey;
1810
1811 /**
1812  * The public information of an RSA key pair.
1813  */
1814 struct GNUNET_CRYPTO_RsaPublicKey;
1815
1816 /**
1817  * Constant-size pre-secret for blinding key generation.
1818  */
1819 struct GNUNET_CRYPTO_RsaBlindingKeySecret
1820 {
1821   /**
1822    * Bits used to generate the blinding key.  256 bits
1823    * of entropy is enough.
1824    */
1825   uint32_t pre_secret[8] GNUNET_PACKED;
1826 };
1827
1828 /**
1829  * @brief an RSA signature
1830  */
1831 struct GNUNET_CRYPTO_RsaSignature;
1832
1833
1834 /**
1835  * Create a new private key. Caller must free return value.
1836  *
1837  * @param len length of the key in bits (i.e. 2048)
1838  * @return fresh private key
1839  */
1840 struct GNUNET_CRYPTO_RsaPrivateKey *
1841 GNUNET_CRYPTO_rsa_private_key_create (unsigned int len);
1842
1843
1844 /**
1845  * Free memory occupied by the private key.
1846  *
1847  * @param key pointer to the memory to free
1848  */
1849 void
1850 GNUNET_CRYPTO_rsa_private_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *key);
1851
1852
1853 /**
1854  * Encode the private key in a format suitable for
1855  * storing it into a file.
1856  *
1857  * @param key the private key
1858  * @param[out] buffer set to a buffer with the encoded key
1859  * @return size of memory allocatedin @a buffer
1860  */
1861 size_t
1862 GNUNET_CRYPTO_rsa_private_key_encode (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
1863                                       char **buffer);
1864
1865
1866 /**
1867  * Decode the private key from the data-format back
1868  * to the "normal", internal format.
1869  *
1870  * @param buf the buffer where the private key data is stored
1871  * @param len the length of the data in @a buf
1872  * @return NULL on error
1873  */
1874 struct GNUNET_CRYPTO_RsaPrivateKey *
1875 GNUNET_CRYPTO_rsa_private_key_decode (const char *buf,
1876                                       size_t len);
1877
1878
1879 /**
1880  * Duplicate the given private key
1881  *
1882  * @param key the private key to duplicate
1883  * @return the duplicate key; NULL upon error
1884  */
1885 struct GNUNET_CRYPTO_RsaPrivateKey *
1886 GNUNET_CRYPTO_rsa_private_key_dup (const struct GNUNET_CRYPTO_RsaPrivateKey *key);
1887
1888
1889 /**
1890  * Extract the public key of the given private key.
1891  *
1892  * @param priv the private key
1893  * @retur NULL on error, otherwise the public key
1894  */
1895 struct GNUNET_CRYPTO_RsaPublicKey *
1896 GNUNET_CRYPTO_rsa_private_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey *priv);
1897
1898
1899 /**
1900  * Compute hash over the public key.
1901  *
1902  * @param key public key to hash
1903  * @param hc where to store the hash code
1904  */
1905 void
1906 GNUNET_CRYPTO_rsa_public_key_hash (const struct GNUNET_CRYPTO_RsaPublicKey *key,
1907                                    struct GNUNET_HashCode *hc);
1908
1909
1910 /**
1911  * Obtain the length of the RSA key in bits.
1912  *
1913  * @param key the public key to introspect
1914  * @return length of the key in bits
1915  */
1916 unsigned int
1917 GNUNET_CRYPTO_rsa_public_key_len (const struct GNUNET_CRYPTO_RsaPublicKey *key);
1918
1919
1920 /**
1921  * Free memory occupied by the public key.
1922  *
1923  * @param key pointer to the memory to free
1924  */
1925 void
1926 GNUNET_CRYPTO_rsa_public_key_free (struct GNUNET_CRYPTO_RsaPublicKey *key);
1927
1928
1929 /**
1930  * Encode the public key in a format suitable for
1931  * storing it into a file.
1932  *
1933  * @param key the private key
1934  * @param[out] buffer set to a buffer with the encoded key
1935  * @return size of memory allocated in @a buffer
1936  */
1937 size_t
1938 GNUNET_CRYPTO_rsa_public_key_encode (const struct GNUNET_CRYPTO_RsaPublicKey *key,
1939                                      char **buffer);
1940
1941
1942 /**
1943  * Decode the public key from the data-format back
1944  * to the "normal", internal format.
1945  *
1946  * @param buf the buffer where the public key data is stored
1947  * @param len the length of the data in @a buf
1948  * @return NULL on error
1949  */
1950 struct GNUNET_CRYPTO_RsaPublicKey *
1951 GNUNET_CRYPTO_rsa_public_key_decode (const char *buf,
1952                                      size_t len);
1953
1954
1955 /**
1956  * Duplicate the given public key
1957  *
1958  * @param key the public key to duplicate
1959  * @return the duplicate key; NULL upon error
1960  */
1961 struct GNUNET_CRYPTO_RsaPublicKey *
1962 GNUNET_CRYPTO_rsa_public_key_dup (const struct GNUNET_CRYPTO_RsaPublicKey *key);
1963
1964
1965 /**
1966  * Compare the values of two signatures.
1967  *
1968  * @param s1 one signature
1969  * @param s2 the other signature
1970  * @return 0 if the two are equal
1971  */
1972 int
1973 GNUNET_CRYPTO_rsa_signature_cmp (struct GNUNET_CRYPTO_RsaSignature *s1,
1974                                  struct GNUNET_CRYPTO_RsaSignature *s2);
1975
1976 /**
1977  * Compare the values of two private keys.
1978  *
1979  * @param p1 one private key
1980  * @param p2 the other private key
1981  * @return 0 if the two are equal
1982  */
1983 int
1984 GNUNET_CRYPTO_rsa_private_key_cmp (struct GNUNET_CRYPTO_RsaPrivateKey *p1,
1985                                   struct GNUNET_CRYPTO_RsaPrivateKey *p2);
1986
1987
1988 /**
1989  * Compare the values of two public keys.
1990  *
1991  * @param p1 one public key
1992  * @param p2 the other public key
1993  * @return 0 if the two are equal
1994  */
1995 int
1996 GNUNET_CRYPTO_rsa_public_key_cmp (struct GNUNET_CRYPTO_RsaPublicKey *p1,
1997                                   struct GNUNET_CRYPTO_RsaPublicKey *p2);
1998
1999
2000 /**
2001  * Blinds the given message with the given blinding key
2002  *
2003  * @param hash hash of the message to sign
2004  * @param bkey the blinding key
2005  * @param pkey the public key of the signer
2006  * @param[out] buf set to a buffer with the blinded message to be signed
2007  * @param[out] buf_size number of bytes stored in @a buf
2008  * @return GNUNET_YES if successful, GNUNET_NO if RSA key is malicious
2009  */
2010 int
2011 GNUNET_CRYPTO_rsa_blind (const struct GNUNET_HashCode *hash,
2012                          const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks,
2013                          struct GNUNET_CRYPTO_RsaPublicKey *pkey,
2014                          char **buf, size_t *buf_size);
2015
2016
2017 /**
2018  * Sign a blinded value, which must be a full domain hash of a message.
2019  *
2020  * @param key private key to use for the signing
2021  * @param msg the (blinded) message to sign
2022  * @param msg_len number of bytes in @a msg to sign
2023  * @return NULL on error, signature on success
2024  */
2025 struct GNUNET_CRYPTO_RsaSignature *
2026 GNUNET_CRYPTO_rsa_sign_blinded (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
2027                                 const void *msg, size_t msg_len);
2028
2029
2030 /**
2031  * Create and sign a full domain hash of a message.
2032  *
2033  * @param key private key to use for the signing
2034  * @param hash the hash of the message to sign
2035  * @return NULL on error, including a malicious RSA key, signature on success
2036  */
2037 struct GNUNET_CRYPTO_RsaSignature *
2038 GNUNET_CRYPTO_rsa_sign_fdh (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
2039                             const struct GNUNET_HashCode *hash);
2040
2041
2042 /**
2043  * Free memory occupied by signature.
2044  *
2045  * @param sig memory to free
2046  */
2047 void
2048 GNUNET_CRYPTO_rsa_signature_free (struct GNUNET_CRYPTO_RsaSignature *sig);
2049
2050
2051 /**
2052  * Encode the given signature in a format suitable for storing it into a file.
2053  *
2054  * @param sig the signature
2055  * @param[out] buffer set to a buffer with the encoded key
2056  * @return size of memory allocated in @a buffer
2057  */
2058 size_t
2059 GNUNET_CRYPTO_rsa_signature_encode (const struct GNUNET_CRYPTO_RsaSignature *sig,
2060                                     char **buffer);
2061
2062
2063 /**
2064  * Decode the signature from the data-format back to the "normal", internal
2065  * format.
2066  *
2067  * @param buf the buffer where the public key data is stored
2068  * @param len the length of the data in @a buf
2069  * @return NULL on error
2070  */
2071 struct GNUNET_CRYPTO_RsaSignature *
2072 GNUNET_CRYPTO_rsa_signature_decode (const char *buf,
2073                                     size_t len);
2074
2075
2076 /**
2077  * Duplicate the given rsa signature
2078  *
2079  * @param sig the signature to duplicate
2080  * @return the duplicate key; NULL upon error
2081  */
2082 struct GNUNET_CRYPTO_RsaSignature *
2083 GNUNET_CRYPTO_rsa_signature_dup (const struct GNUNET_CRYPTO_RsaSignature *sig);
2084
2085
2086 /**
2087  * Unblind a blind-signed signature.  The signature should have been generated
2088  * with #GNUNET_CRYPTO_rsa_sign() using a hash that was blinded with
2089  * #GNUNET_CRYPTO_rsa_blind().
2090  *
2091  * @param sig the signature made on the blinded signature purpose
2092  * @param bks the blinding key secret used to blind the signature purpose
2093  * @param pkey the public key of the signer
2094  * @return unblinded signature on success, NULL if RSA key is bad or malicious.
2095  */
2096 struct GNUNET_CRYPTO_RsaSignature *
2097 GNUNET_CRYPTO_rsa_unblind (struct GNUNET_CRYPTO_RsaSignature *sig,
2098                            const struct GNUNET_CRYPTO_RsaBlindingKeySecret *bks,
2099                            struct GNUNET_CRYPTO_RsaPublicKey *pkey);
2100
2101
2102 /**
2103  * Verify whether the given hash corresponds to the given signature and the
2104  * signature is valid with respect to the given public key.
2105  *
2106  * @param hash the message to verify to match the @a sig
2107  * @param sig signature that is being validated
2108  * @param public_key public key of the signer
2109  * @returns #GNUNET_YES if ok, #GNUNET_NO if RSA key is malicious, #GNUNET_SYSERR if signature
2110  */
2111 int
2112 GNUNET_CRYPTO_rsa_verify (const struct GNUNET_HashCode *hash,
2113                           const struct GNUNET_CRYPTO_RsaSignature *sig,
2114                           const struct GNUNET_CRYPTO_RsaPublicKey *public_key);
2115
2116
2117 #if 0                           /* keep Emacsens' auto-indent happy */
2118 {
2119 #endif
2120 #ifdef __cplusplus
2121 }
2122 #endif
2123
2124
2125 /* ifndef GNUNET_CRYPTO_LIB_H */
2126 #endif
2127 /* end of gnunet_crypto_lib.h */