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