2 This file is part of GNUnet.
3 (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Christian Grothoff (and other contributing authors)
5 GNUnet is free software; you can redistribute it and/or modify
6 it under the terms of the GNU General Public License as published
7 by the Free Software Foundation; either version 2, or (at your
8 option) any later version.
10 GNUnet is distributed in the hope that it will be useful, but
11 WITHOUT ANY WARRANTY; without even the implied warranty of
12 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
13 General Public License for more details.
15 You should have received a copy of the GNU General Public License
16 along with GNUnet; see the file COPYING. If not, write to the
17 Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18 Boston, MA 02111-1307, USA.
22 * @file include/gnunet_crypto_lib.h
23 * @brief cryptographic primitives for GNUnet
25 * @author Christian Grothoff
26 * @author Krista Bennett
27 * @author Gerd Knorr <kraxel@bytesex.org>
28 * @author Ioana Patrascu
29 * @author Tzvetan Horozov
32 #ifndef GNUNET_CRYPTO_LIB_H
33 #define GNUNET_CRYPTO_LIB_H
38 #if 0 /* keep Emacsens' auto-indent happy */
43 #include "gnunet_common.h"
44 #include "gnunet_scheduler_lib.h"
47 * Desired quality level for cryptographic operations.
49 enum GNUNET_CRYPTO_Quality
52 * No good quality of the operation is needed (i.e.,
53 * random numbers can be pseudo-random).
55 GNUNET_CRYPTO_QUALITY_WEAK,
58 * High-quality operations are desired.
60 GNUNET_CRYPTO_QUALITY_STRONG,
63 * Randomness for IVs etc. is required.
65 GNUNET_CRYPTO_QUALITY_NONCE
70 * @brief length of the sessionkey in bytes (256 BIT sessionkey)
72 #define GNUNET_CRYPTO_AES_KEY_LENGTH (256/8)
76 * @brief Length of RSA encrypted data (2048 bit)
78 * We currently do not handle encryption of data
79 * that can not be done in a single call to the
80 * RSA methods (read: large chunks of data).
81 * We should never need that, as we can use
82 * the GNUNET_CRYPTO_hash for larger pieces of data for signing,
83 * and for encryption, we only need to encode sessionkeys!
85 #define GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH 256
89 * Length of an RSA KEY (d,e,len), 2048 bit (=256 octests) key d, 2 byte e
91 #define GNUNET_CRYPTO_RSA_KEY_LENGTH 258
95 * Length of a hash value
97 #define GNUNET_CRYPTO_HASH_LENGTH 512/8
100 * The private information of an RSA key pair.
102 struct GNUNET_CRYPTO_RsaPrivateKey;
106 * @brief 0-terminated ASCII encoding of a GNUNET_HashCode.
108 struct GNUNET_CRYPTO_HashAsciiEncoded
110 unsigned char encoding[104];
116 * @brief an RSA signature
118 struct GNUNET_CRYPTO_RsaSignature
120 unsigned char sig[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
125 * @brief header of what an RSA signature signs
126 * this must be followed by "size - 8" bytes of
127 * the actual signed data
129 struct GNUNET_CRYPTO_RsaSignaturePurpose
132 * How many bytes does this signature sign?
133 * (including this purpose header); in network
136 uint32_t size GNUNET_PACKED;
139 * What does this signature vouch for? This
140 * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
141 * constant (from gnunet_signatures.h). In
142 * network byte order!
144 uint32_t purpose GNUNET_PACKED;
150 * @brief A public key.
152 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
155 * In big-endian, must be GNUNET_CRYPTO_RSA_KEY_LENGTH+4
157 uint16_t len GNUNET_PACKED;
160 * Size of n in key; in big-endian!
162 uint16_t sizen GNUNET_PACKED;
165 * The key itself, contains n followed by e.
167 unsigned char key[GNUNET_CRYPTO_RSA_KEY_LENGTH];
170 * Padding (must be 0)
172 uint16_t padding GNUNET_PACKED;
177 * RSA Encrypted data.
179 struct GNUNET_CRYPTO_RsaEncryptedData
181 unsigned char encoding[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
186 * @brief type for session keys
188 struct GNUNET_CRYPTO_AesSessionKey
193 unsigned char key[GNUNET_CRYPTO_AES_KEY_LENGTH];
198 uint32_t crc32 GNUNET_PACKED;
203 * @brief IV for sym cipher
205 * NOTE: must be smaller (!) in size than the
208 struct GNUNET_CRYPTO_AesInitializationVector
210 unsigned char iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
215 * @brief type for (message) authentication keys
217 struct GNUNET_CRYPTO_AuthKey
219 unsigned char key[GNUNET_CRYPTO_HASH_LENGTH];
223 /* **************** Functions and Macros ************* */
227 * Compute the CRC32 checksum for the first len
228 * bytes of the buffer.
230 * @param buf the data over which we're taking the CRC
231 * @param len the length of the buffer in bytes
232 * @return the resulting CRC32 checksum
234 int32_t GNUNET_CRYPTO_crc32_n (const void *buf, size_t len);
238 * Produce a random value.
240 * @param mode desired quality of the random number
241 * @param i the upper limit (exclusive) for the random number
242 * @return a random value in the interval [0,i) (exclusive).
244 uint32_t GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode, uint32_t i);
248 * Random on unsigned 64-bit values.
250 * @param mode desired quality of the random number
251 * @param max value returned will be in range [0,max) (exclusive)
252 * @return random 64-bit number
254 uint64_t GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode,
259 * Get an array with a random permutation of the
261 * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
262 * @param n the size of the array
263 * @return the permutation array (allocated from heap)
265 unsigned int *GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
270 * Create a new Session key.
272 * @param key key to initialize
274 void GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey
278 * Check that a new session key is well-formed.
280 * @param key key to check
281 * @return GNUNET_OK if the key is valid
283 int GNUNET_CRYPTO_aes_check_session_key (const struct
284 GNUNET_CRYPTO_AesSessionKey *key);
288 * Encrypt a block with the public key of another
289 * host that uses the same cyper.
291 * @param block the block to encrypt
292 * @param len the size of the block
293 * @param sessionkey the key used to encrypt
294 * @param iv the initialization vector to use, use INITVALUE
296 * @return the size of the encrypted block, -1 for errors
298 ssize_t GNUNET_CRYPTO_aes_encrypt (const void *block, size_t len,
299 const struct GNUNET_CRYPTO_AesSessionKey
302 GNUNET_CRYPTO_AesInitializationVector *iv,
307 * Decrypt a given block with the sessionkey.
309 * @param block the data to decrypt, encoded as returned by encrypt
310 * @param size how big is the block?
311 * @param sessionkey the key used to decrypt
312 * @param iv the initialization vector to use
313 * @param result address to store the result at
314 * @return -1 on failure, size of decrypted block on success
316 ssize_t GNUNET_CRYPTO_aes_decrypt (const void *block, size_t size,
317 const struct GNUNET_CRYPTO_AesSessionKey
320 GNUNET_CRYPTO_AesInitializationVector *iv,
325 * @brief Derive an IV
326 * @param iv initialization vector
327 * @param skey session key
328 * @param salt salt for the derivation
329 * @param salt_len size of the salt
330 * @param ... pairs of void * & size_t for context chunks, terminated by NULL
332 void GNUNET_CRYPTO_aes_derive_iv (struct GNUNET_CRYPTO_AesInitializationVector
334 const struct GNUNET_CRYPTO_AesSessionKey
335 *skey, const void *salt, size_t salt_len,
340 * @brief Derive an IV
341 * @param iv initialization vector
342 * @param skey session key
343 * @param salt salt for the derivation
344 * @param salt_len size of the salt
345 * @param argp pairs of void * & size_t for context chunks, terminated by NULL
347 void GNUNET_CRYPTO_aes_derive_iv_v (struct GNUNET_CRYPTO_AesInitializationVector
349 const struct GNUNET_CRYPTO_AesSessionKey
350 *skey, const void *salt, size_t salt_len,
355 * Convert hash to ASCII encoding.
356 * @param block the hash code
357 * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
358 * safely cast to char*, a '\\0' termination is set).
360 void GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
361 struct GNUNET_CRYPTO_HashAsciiEncoded *result);
365 * Convert ASCII encoding back to GNUNET_CRYPTO_hash
366 * @param enc the encoding
367 * @param result where to store the GNUNET_CRYPTO_hash code
368 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
370 int GNUNET_CRYPTO_hash_from_string (const char *enc, GNUNET_HashCode * result);
374 * Compute the distance between 2 hashcodes.
375 * The computation must be fast, not involve
376 * a.a or a.e (they're used elsewhere), and
377 * be somewhat consistent. And of course, the
378 * result should be a positive number.
380 * @param a some hash code
381 * @param b some hash code
382 * @return number between 0 and UINT32_MAX
384 uint32_t GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
385 const GNUNET_HashCode * b);
389 * Compute hash of a given block.
391 * @param block the data to hash
392 * @param size size of the block
393 * @param ret pointer to where to write the hashcode
395 void GNUNET_CRYPTO_hash (const void *block, size_t size, GNUNET_HashCode * ret);
399 * Calculate HMAC of a message (RFC 2104)
401 * @param key secret key
402 * @param plaintext input plaintext
403 * @param plaintext_len length of plaintext
404 * @param hmac where to store the hmac
406 void GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
407 const void *plaintext, size_t plaintext_len,
408 GNUNET_HashCode * hmac);
412 * Function called once the hash computation over the
413 * specified file has completed.
416 * @param res resulting hash, NULL on error
418 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
419 const GNUNET_HashCode *
424 * Handle to file hashing operation.
426 struct GNUNET_CRYPTO_FileHashContext;
429 * Compute the hash of an entire file.
431 * @param priority scheduling priority to use
432 * @param filename name of file to hash
433 * @param blocksize number of bytes to process in one task
434 * @param callback function to call upon completion
435 * @param callback_cls closure for callback
436 * @return NULL on (immediate) errror
438 struct GNUNET_CRYPTO_FileHashContext *GNUNET_CRYPTO_hash_file (enum
439 GNUNET_SCHEDULER_Priority
444 GNUNET_CRYPTO_HashCompletedCallback
451 * Cancel a file hashing operation.
453 * @param fhc operation to cancel (callback must not yet have been invoked)
455 void GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
459 * Create a random hash code.
461 * @param mode desired quality level
462 * @param result hash code that is randomized
464 void GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
465 GNUNET_HashCode * result);
469 * compute result(delta) = b - a
471 * @param a some hash code
472 * @param b some hash code
473 * @param result set to b - a
475 void GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
476 const GNUNET_HashCode * b,
477 GNUNET_HashCode * result);
481 * compute result(b) = a + delta
483 * @param a some hash code
484 * @param delta some hash code
485 * @param result set to a + delta
487 void GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
488 const GNUNET_HashCode * delta,
489 GNUNET_HashCode * result);
493 * compute result = a ^ b
495 * @param a some hash code
496 * @param b some hash code
497 * @param result set to a ^ b
499 void GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
500 const GNUNET_HashCode * b,
501 GNUNET_HashCode * result);
505 * Convert a hashcode into a key.
507 * @param hc hash code that serves to generate the key
508 * @param skey set to a valid session key
509 * @param iv set to a valid initialization vector
511 void GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
512 struct GNUNET_CRYPTO_AesSessionKey *skey,
513 struct GNUNET_CRYPTO_AesInitializationVector
518 * Obtain a bit from a hashcode.
520 * @param code the GNUNET_CRYPTO_hash to index bit-wise
521 * @param bit index into the hashcode, [0...159]
522 * @return Bit \a bit from hashcode \a code, -1 for invalid index
524 int GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code, unsigned int bit);
527 * Determine how many low order bits match in two
528 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
529 * the first two lowest order bits, and therefore the
530 * return value is two (NOT XOR distance, nor how many
531 * bits match absolutely!).
533 * @param first the first hashcode
534 * @param second the hashcode to compare first to
536 * @return the number of bits that match
538 unsigned int GNUNET_CRYPTO_hash_matching_bits (const GNUNET_HashCode * first,
539 const GNUNET_HashCode * second);
543 * Compare function for HashCodes, producing a total ordering
546 * @param h1 some hash code
547 * @param h2 some hash code
548 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
550 int GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
551 const GNUNET_HashCode * h2);
555 * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
556 * in the XOR metric (Kademlia).
558 * @param h1 some hash code
559 * @param h2 some hash code
560 * @param target some hash code
561 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
563 int GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
564 const GNUNET_HashCode * h2,
565 const GNUNET_HashCode * target);
569 * @brief Derive an authentication key
570 * @param key authentication key
571 * @param rkey root key
573 * @param salt_len size of the salt
574 * @param argp pair of void * & size_t for context chunks, terminated by NULL
576 void GNUNET_CRYPTO_hmac_derive_key_v (struct GNUNET_CRYPTO_AuthKey *key,
577 const struct GNUNET_CRYPTO_AesSessionKey
578 *rkey, const void *salt, size_t salt_len,
583 * @brief Derive an authentication key
584 * @param key authentication key
585 * @param rkey root key
587 * @param salt_len size of the salt
588 * @param ... pair of void * & size_t for context chunks, terminated by NULL
590 void GNUNET_CRYPTO_hmac_derive_key (struct GNUNET_CRYPTO_AuthKey *key,
591 const struct GNUNET_CRYPTO_AesSessionKey
592 *rkey, const void *salt, size_t salt_len,
597 * @param result buffer for the derived key, allocated by caller
598 * @param out_len desired length of the derived key
599 * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
600 * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
602 * @param xts_len length of xts
603 * @param skm source key material
604 * @param skm_len length of skm
605 * @return GNUNET_YES on success
607 int GNUNET_CRYPTO_hkdf (void *result, size_t out_len, int xtr_algo,
608 int prf_algo, const void *xts, size_t xts_len,
609 const void *skm, size_t skm_len, ...);
614 * @param result buffer for the derived key, allocated by caller
615 * @param out_len desired length of the derived key
616 * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
617 * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
619 * @param xts_len length of xts
620 * @param skm source key material
621 * @param skm_len length of skm
622 * @param argp va_list of void * & size_t pairs for context chunks
623 * @return GNUNET_YES on success
625 int GNUNET_CRYPTO_hkdf_v (void *result, size_t out_len, int xtr_algo,
626 int prf_algo, const void *xts, size_t xts_len,
627 const void *skm, size_t skm_len, va_list argp);
632 * @param result buffer for the derived key, allocated by caller
633 * @param out_len desired length of the derived key
635 * @param xts_len length of xts
636 * @param skm source key material
637 * @param skm_len length of skm
638 * @param argp va_list of void * & size_t pairs for context chunks
639 * @return GNUNET_YES on success
641 int GNUNET_CRYPTO_kdf_v (void *result, size_t out_len, const void *xts,
642 size_t xts_len, const void *skm, size_t skm_len,
648 * @param result buffer for the derived key, allocated by caller
649 * @param out_len desired length of the derived key
651 * @param xts_len length of xts
652 * @param skm source key material
653 * @param skm_len length of skm
654 * @param ... void * & size_t pairs for context chunks
655 * @return GNUNET_YES on success
657 int GNUNET_CRYPTO_kdf (void *result, size_t out_len, const void *xts,
658 size_t xts_len, const void *skm, size_t skm_len, ...);
662 * Create a new private key. Caller must free return value.
664 * @return fresh private key
666 struct GNUNET_CRYPTO_RsaPrivateKey *GNUNET_CRYPTO_rsa_key_create (void);
669 * Decode the private key from the data-format back
670 * to the "normal", internal format.
672 * @param buf the buffer where the private key data is stored
673 * @param len the length of the data in 'buffer'
675 struct GNUNET_CRYPTO_RsaPrivateKey *GNUNET_CRYPTO_rsa_decode_key (const char
680 * Create a new private key by reading it from a file. If the
681 * files does not exist, create a new key and write it to the
682 * file. Caller must free return value. Note that this function
683 * can not guarantee that another process might not be trying
684 * the same operation on the same file at the same time.
685 * If the contents of the file
686 * are invalid the old file is deleted and a fresh key is
689 * @param filename name of file to use for storage
690 * @return new private key, NULL on error (for example,
693 struct GNUNET_CRYPTO_RsaPrivateKey
694 *GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
698 * Deterministically (!) create a private key using only the
699 * given HashCode as input to the PRNG.
701 * @param hc "random" input to PRNG
702 * @return some private key purely dependent on input
704 struct GNUNET_CRYPTO_RsaPrivateKey
705 *GNUNET_CRYPTO_rsa_key_create_from_hash (const GNUNET_HashCode * hc);
709 * Free memory occupied by the private key.
710 * @param hostkey pointer to the memory to free
712 void GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
716 * Extract the public key of the host.
718 * @param priv the private key
719 * @param pub where to write the public key
721 void GNUNET_CRYPTO_rsa_key_get_public (const struct GNUNET_CRYPTO_RsaPrivateKey
724 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
729 * Encrypt a block with the public key of another host that uses the
732 * @param block the block to encrypt
733 * @param size the size of block
734 * @param publicKey the encoded public key used to encrypt
735 * @param target where to store the encrypted block
736 * @return GNUNET_SYSERR on error, GNUNET_OK if ok
738 int GNUNET_CRYPTO_rsa_encrypt (const void *block, size_t size,
740 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
742 struct GNUNET_CRYPTO_RsaEncryptedData *target);
746 * Decrypt a given block with the hostkey.
748 * @param key the key to use
749 * @param block the data to decrypt, encoded as returned by encrypt, not consumed
750 * @param result pointer to a location where the result can be stored
751 * @param max how many bytes of a result are expected? Must be exact.
752 * @return the size of the decrypted block (that is, size) or -1 on error
754 ssize_t GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey
756 const struct GNUNET_CRYPTO_RsaEncryptedData
757 *block, void *result, size_t max);
761 * Sign a given block.
763 * @param key private key to use for the signing
764 * @param purpose what to sign (size, purpose)
765 * @param sig where to write the signature
766 * @return GNUNET_SYSERR on error, GNUNET_OK on success
768 int GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
769 const struct GNUNET_CRYPTO_RsaSignaturePurpose
770 *purpose, struct GNUNET_CRYPTO_RsaSignature *sig);
774 * Verify signature. Note that the caller MUST have already
775 * checked that "validate->size" bytes are actually available.
777 * @param purpose what is the purpose that validate should have?
778 * @param validate block to validate (size, purpose, data)
779 * @param sig signature that is being validated
780 * @param publicKey public key of the signer
781 * @return GNUNET_OK if ok, GNUNET_SYSERR if invalid
783 int GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
784 const struct GNUNET_CRYPTO_RsaSignaturePurpose
786 const struct GNUNET_CRYPTO_RsaSignature *sig,
788 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
794 * This function should only be called in testcases
795 * where strong entropy gathering is not desired
796 * (for example, for hostkey generation).
798 void GNUNET_CRYPTO_random_disable_entropy_gathering (void);
800 #if 0 /* keep Emacsens' auto-indent happy */
808 /* ifndef GNUNET_CRYPTO_LIB_H */
810 /* end of gnunet_crypto_lib.h */