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