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