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