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