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,
239 * Produce a random value.
241 * @param mode desired quality of the random number
242 * @param i the upper limit (exclusive) for the random number
243 * @return a random value in the interval [0,i) (exclusive).
245 uint32_t GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode,
250 * Random on unsigned 64-bit values.
252 * @param mode desired quality of the random number
253 * @param max value returned will be in range [0,max) (exclusive)
254 * @return random 64-bit number
256 uint64_t GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode,
261 * Get an array with a random permutation of the
263 * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
264 * @param n the size of the array
265 * @return the permutation array (allocated from heap)
267 unsigned int *GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
272 * Create a new Session key.
274 * @param key key to initialize
276 void GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey
280 * Check that a new session key is well-formed.
282 * @param key key to check
283 * @return GNUNET_OK if the key is valid
285 int GNUNET_CRYPTO_aes_check_session_key (const struct
286 GNUNET_CRYPTO_AesSessionKey *key);
290 * Encrypt a block with the public key of another
291 * host that uses the same cyper.
293 * @param block the block to encrypt
294 * @param len the size of the block
295 * @param sessionkey the key used to encrypt
296 * @param iv the initialization vector to use, use INITVALUE
298 * @return the size of the encrypted block, -1 for errors
300 ssize_t GNUNET_CRYPTO_aes_encrypt (const void *block,
302 const struct GNUNET_CRYPTO_AesSessionKey
305 GNUNET_CRYPTO_AesInitializationVector *iv,
310 * Decrypt a given block with the sessionkey.
312 * @param block the data to decrypt, encoded as returned by encrypt
313 * @param size how big is the block?
314 * @param sessionkey the key used to decrypt
315 * @param iv the initialization vector to use
316 * @param result address to store the result at
317 * @return -1 on failure, size of decrypted block on success
319 ssize_t GNUNET_CRYPTO_aes_decrypt (const void *block,
321 const struct GNUNET_CRYPTO_AesSessionKey *sessionkey,
322 const struct GNUNET_CRYPTO_AesInitializationVector *iv,
327 * @brief Derive an IV
328 * @param iv initialization vector
329 * @param skey session key
330 * @param salt salt for the derivation
331 * @param salt_len size of the salt
332 * @param ... pairs of void * & size_t for context chunks, terminated by NULL
335 GNUNET_CRYPTO_aes_derive_iv (struct GNUNET_CRYPTO_AesInitializationVector *iv,
336 const struct GNUNET_CRYPTO_AesSessionKey *skey, void *salt,
337 size_t salt_len, ...);
341 * @brief Derive an IV
342 * @param iv initialization vector
343 * @param skey session key
344 * @param salt salt for the derivation
345 * @param salt_len size of the salt
346 * @param argp pairs of void * & size_t for context chunks, terminated by NULL
349 GNUNET_CRYPTO_aes_derive_iv_v (struct GNUNET_CRYPTO_AesInitializationVector *iv,
350 const struct GNUNET_CRYPTO_AesSessionKey *skey, void *salt,
351 size_t salt_len, va_list argp);
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
366 * Convert ASCII encoding back to GNUNET_CRYPTO_hash
367 * @param enc the encoding
368 * @param result where to store the GNUNET_CRYPTO_hash code
369 * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
371 int GNUNET_CRYPTO_hash_from_string (const char *enc,
372 GNUNET_HashCode * result);
376 * Compute the distance between 2 hashcodes.
377 * The computation must be fast, not involve
378 * a.a or a.e (they're used elsewhere), and
379 * be somewhat consistent. And of course, the
380 * result should be a positive number.
382 * @param a some hash code
383 * @param b some hash code
384 * @return number between 0 and UINT32_MAX
386 uint32_t GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
387 const GNUNET_HashCode * b);
391 * Compute hash of a given block.
393 * @param block the data to hash
394 * @param size size of the block
395 * @param ret pointer to where to write the hashcode
397 void GNUNET_CRYPTO_hash (const void *block,
399 GNUNET_HashCode * ret);
403 * Calculate HMAC of a message (RFC 2104)
405 * @param key secret key
406 * @param plaintext input plaintext
407 * @param plaintext_len length of plaintext
408 * @param hmac where to store the hmac
411 GNUNET_CRYPTO_hmac (const struct GNUNET_CRYPTO_AuthKey *key,
412 const void *plaintext,
413 size_t plaintext_len,
414 GNUNET_HashCode *hmac);
418 * Function called once the hash computation over the
419 * specified file has completed.
422 * @param res resulting hash, NULL on error
424 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
425 const GNUNET_HashCode *
430 * Handle to file hashing operation.
432 struct GNUNET_CRYPTO_FileHashContext;
435 * Compute the hash of an entire file.
437 * @param sched scheduler to use
438 * @param priority scheduling priority to use
439 * @param filename name of file to hash
440 * @param blocksize number of bytes to process in one task
441 * @param callback function to call upon completion
442 * @param callback_cls closure for callback
443 * @return NULL on (immediate) errror
445 struct GNUNET_CRYPTO_FileHashContext *
446 GNUNET_CRYPTO_hash_file (struct GNUNET_SCHEDULER_Handle *sched,
447 enum GNUNET_SCHEDULER_Priority priority,
448 const char *filename,
450 GNUNET_CRYPTO_HashCompletedCallback callback,
455 * Cancel a file hashing operation.
457 * @param fhc operation to cancel (callback must not yet have been invoked)
460 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
464 * Create a random hash code.
466 * @param mode desired quality level
467 * @param result hash code that is randomized
469 void GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
470 GNUNET_HashCode * result);
474 * compute result(delta) = b - a
476 * @param a some hash code
477 * @param b some hash code
478 * @param result set to b - a
480 void GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
481 const GNUNET_HashCode * b,
482 GNUNET_HashCode * result);
486 * compute result(b) = a + delta
488 * @param a some hash code
489 * @param delta some hash code
490 * @param result set to a + delta
492 void GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
493 const GNUNET_HashCode * delta,
494 GNUNET_HashCode * result);
498 * compute result = a ^ b
500 * @param a some hash code
501 * @param b some hash code
502 * @param result set to a ^ b
504 void GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
505 const GNUNET_HashCode * b,
506 GNUNET_HashCode * result);
510 * Convert a hashcode into a key.
512 * @param hc hash code that serves to generate the key
513 * @param skey set to a valid session key
514 * @param iv set to a valid initialization vector
516 void GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
517 struct GNUNET_CRYPTO_AesSessionKey *skey,
519 GNUNET_CRYPTO_AesInitializationVector
524 * Obtain a bit from a hashcode.
526 * @param code the GNUNET_CRYPTO_hash to index bit-wise
527 * @param bit index into the hashcode, [0...159]
528 * @return Bit \a bit from hashcode \a code, -1 for invalid index
530 int GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code,
534 * Determine how many low order bits match in two
535 * GNUNET_HashCodes. i.e. - 010011 and 011111 share
536 * the first two lowest order bits, and therefore the
537 * return value is two (NOT XOR distance, nor how many
538 * bits match absolutely!).
540 * @param first the first hashcode
541 * @param second the hashcode to compare first to
543 * @return the number of bits that match
545 unsigned int GNUNET_CRYPTO_hash_matching_bits(const GNUNET_HashCode *first, const GNUNET_HashCode *second);
549 * Compare function for HashCodes, producing a total ordering
552 * @param h1 some hash code
553 * @param h2 some hash code
554 * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
556 int GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
557 const GNUNET_HashCode * h2);
561 * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
562 * in the XOR metric (Kademlia).
564 * @param h1 some hash code
565 * @param h2 some hash code
566 * @param target some hash code
567 * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
569 int GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
570 const GNUNET_HashCode * h2,
571 const GNUNET_HashCode * target);
575 * @brief Derive an authentication key
576 * @param key authentication key
577 * @param rkey root key
579 * @param salt_len size of the salt
580 * @param argp pair of void * & size_t for context chunks, terminated by NULL
583 GNUNET_CRYPTO_hmac_derive_key_v(struct GNUNET_CRYPTO_AuthKey *key,
584 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
586 const size_t salt_len,
591 * @brief Derive an authentication key
592 * @param key authentication key
593 * @param rkey root key
595 * @param salt_len size of the salt
596 * @param ... pair of void * & size_t for context chunks, terminated by NULL
599 GNUNET_CRYPTO_hmac_derive_key(struct GNUNET_CRYPTO_AuthKey *key,
600 const struct GNUNET_CRYPTO_AesSessionKey *rkey,
602 const size_t salt_len,
607 * @param result buffer for the derived key, allocated by caller
608 * @param out_len desired length of the derived key
609 * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
610 * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
612 * @param xts_len length of xts
613 * @param skm source key material
614 * @param skm_len length of skm
615 * @param ctx context info
616 * @param ctx_len length of ctx
617 * @return GNUNET_YES on success
620 GNUNET_CRYPTO_hkdf (void *result, const unsigned long long out_len,
621 int xtr_algo, int prf_algo, const void *xts, const size_t xts_len,
622 const void *skm, const size_t skm_len, ...);
627 * @param result buffer for the derived key, allocated by caller
628 * @param out_len desired length of the derived key
629 * @param xtr_algo hash algorithm for the extraction phase, GCRY_MD_...
630 * @param prf_algo hash algorithm for the expansion phase, GCRY_MD_...
632 * @param xts_len length of xts
633 * @param skm source key material
634 * @param skm_len length of skm
635 * @param argp va_list of void * & size_t pairs for context chunks
636 * @return GNUNET_YES on success
639 GNUNET_CRYPTO_hkdf_v (void *result, const unsigned long long out_len,
640 int xtr_algo, int prf_algo, const void *xts, const size_t xts_len,
641 const void *skm, const size_t skm_len, va_list argp);
646 * @param result buffer for the derived key, allocated by caller
647 * @param out_len desired length of the derived key
649 * @param xts_len length of xts
650 * @param skm source key material
651 * @param skm_len length of skm
652 * @param argp va_list of void * & size_t pairs for context chunks
653 * @return GNUNET_YES on success
656 GNUNET_CRYPTO_kdf_v (void *result, const unsigned long long out_len,
657 const void *xts, const size_t xts_len, const void *skm,
658 const size_t skm_len, va_list argp);
663 * @param result buffer for the derived key, allocated by caller
664 * @param out_len desired length of the derived key
666 * @param xts_len length of xts
667 * @param skm source key material
668 * @param skm_len length of skm
669 * @param ... void * & size_t pairs for context chunks
670 * @return GNUNET_YES on success
673 GNUNET_CRYPTO_kdf (void *result, const unsigned long long out_len,
674 const void *xts, const size_t xts_len, const void *skm,
675 const size_t skm_len, ...);
679 * Create a new private key. Caller must free return value.
681 * @return fresh private key
683 struct GNUNET_CRYPTO_RsaPrivateKey *GNUNET_CRYPTO_rsa_key_create (void);
687 * Create a new private key by reading it from a file. If the
688 * files does not exist, create a new key and write it to the
689 * file. Caller must free return value. Note that this function
690 * can not guarantee that another process might not be trying
691 * the same operation on the same file at the same time.
692 * If the contents of the file
693 * are invalid the old file is deleted and a fresh key is
696 * @param filename name of file to use for storage
697 * @return new private key, NULL on error (for example,
700 struct GNUNET_CRYPTO_RsaPrivateKey
701 *GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
705 * Deterministically (!) create a private key using only the
706 * given HashCode as input to the PRNG.
708 * @param hc "random" input to PRNG
709 * @return some private key purely dependent on input
711 struct GNUNET_CRYPTO_RsaPrivateKey
712 *GNUNET_CRYPTO_rsa_key_create_from_hash (const GNUNET_HashCode * hc);
716 * Free memory occupied by the private key.
717 * @param hostkey pointer to the memory to free
719 void GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
723 * Extract the public key of the host.
725 * @param priv the private key
726 * @param pub where to write the public key
728 void GNUNET_CRYPTO_rsa_key_get_public (const struct
729 GNUNET_CRYPTO_RsaPrivateKey *priv,
731 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
736 * Encrypt a block with the public key of another host that uses the
739 * @param block the block to encrypt
740 * @param size the size of block
741 * @param publicKey the encoded public key used to encrypt
742 * @param target where to store the encrypted block
743 * @return GNUNET_SYSERR on error, GNUNET_OK if ok
745 int GNUNET_CRYPTO_rsa_encrypt (const void *block,
748 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
750 struct GNUNET_CRYPTO_RsaEncryptedData *target);
754 * Decrypt a given block with the hostkey.
756 * @param key the key to use
757 * @param block the data to decrypt, encoded as returned by encrypt, not consumed
758 * @param result pointer to a location where the result can be stored
759 * @param max how many bytes of a result are expected? Must be exact.
760 * @return the size of the decrypted block (that is, size) or -1 on error
762 ssize_t GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
763 const struct GNUNET_CRYPTO_RsaEncryptedData
770 * Sign a given block.
772 * @param key private key to use for the signing
773 * @param purpose what to sign (size, purpose)
774 * @param sig where to write the signature
775 * @return GNUNET_SYSERR on error, GNUNET_OK on success
777 int GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
778 const struct GNUNET_CRYPTO_RsaSignaturePurpose
780 struct GNUNET_CRYPTO_RsaSignature *sig);
784 * Verify signature. Note that the caller MUST have already
785 * checked that "validate->size" bytes are actually available.
787 * @param purpose what is the purpose that validate should have?
788 * @param validate block to validate (size, purpose, data)
789 * @param sig signature that is being validated
790 * @param publicKey public key of the signer
791 * @return GNUNET_OK if ok, GNUNET_SYSERR if invalid
793 int GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
794 const struct GNUNET_CRYPTO_RsaSignaturePurpose
796 const struct GNUNET_CRYPTO_RsaSignature *sig,
798 GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
804 * This function should only be called in testcases
805 * where strong entropy gathering is not desired
806 * (for example, for hostkey generation).
808 void GNUNET_CRYPTO_random_disable_entropy_gathering (void);
810 #if 0 /* keep Emacsens' auto-indent happy */
818 /* ifndef GNUNET_CRYPTO_LIB_H */
820 /* end of gnunet_crypto_lib.h */