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