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