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