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