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