oops, missing commit
[oweals/gnunet.git] / src / include / gnunet_crypto_lib.h
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2007 Christian Grothoff (and other contributing authors)
4
5      GNUnet is free software; you can redistribute it and/or modify
6      it under the terms of the GNU General Public License as published
7      by the Free Software Foundation; either version 2, or (at your
8      option) any later version.
9
10      GNUnet is distributed in the hope that it will be useful, but
11      WITHOUT ANY WARRANTY; without even the implied warranty of
12      MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13      General Public License for more details.
14
15      You should have received a copy of the GNU General Public License
16      along with GNUnet; see the file COPYING.  If not, write to the
17      Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18      Boston, MA 02111-1307, USA.
19 */
20
21 /**
22  * @file include/gnunet_crypto_lib.h
23  * @brief cryptographic primitives for GNUnet
24  *
25  * @author Christian Grothoff
26  * @author Krista Bennett
27  * @author Gerd Knorr <kraxel@bytesex.org>
28  * @author Ioana Patrascu
29  * @author Tzvetan Horozov
30  */
31
32 #ifndef GNUNET_CRYPTO_LIB_H
33 #define GNUNET_CRYPTO_LIB_H
34
35 #ifdef __cplusplus
36 extern "C"
37 {
38 #if 0                           /* keep Emacsens' auto-indent happy */
39 }
40 #endif
41 #endif
42
43 #include "gnunet_common.h"
44 #include "gnunet_scheduler_lib.h"
45
46 /**
47  * Desired quality level for cryptographic operations.
48  */
49 enum GNUNET_CRYPTO_Quality
50 {
51   /**
52    * No good quality of the operation is needed (i.e.,
53    * random numbers can be pseudo-random).
54    */
55   GNUNET_CRYPTO_QUALITY_WEAK,
56
57   /**
58    * High-quality operations are desired.
59    */
60   GNUNET_CRYPTO_QUALITY_STRONG
61 };
62
63
64 /**
65  * @brief length of the sessionkey in bytes (256 BIT sessionkey)
66  */
67 #define GNUNET_CRYPTO_AES_KEY_LENGTH (256/8)
68
69
70 /**
71  * @brief Length of RSA encrypted data (2048 bit)
72  *
73  * We currently do not handle encryption of data
74  * that can not be done in a single call to the
75  * RSA methods (read: large chunks of data).
76  * We should never need that, as we can use
77  * the GNUNET_CRYPTO_hash for larger pieces of data for signing,
78  * and for encryption, we only need to encode sessionkeys!
79  */
80 #define GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH 256
81
82
83 /**
84  * Length of an RSA KEY (d,e,len), 2048 bit (=256 octests) key d, 2 byte e
85  */
86 #define GNUNET_CRYPTO_RSA_KEY_LENGTH 258
87
88
89 /**
90  * The private information of an RSA key pair.
91  */
92 struct GNUNET_CRYPTO_RsaPrivateKey;
93
94
95 /**
96  * @brief 0-terminated ASCII encoding of a GNUNET_HashCode.
97  */
98 struct GNUNET_CRYPTO_HashAsciiEncoded
99 {
100   unsigned char encoding[104];
101 };
102
103
104
105 /**
106  * @brief an RSA signature
107  */
108 struct GNUNET_CRYPTO_RsaSignature
109 {
110   unsigned char sig[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
111 };
112
113
114 /**
115  * @brief header of what an RSA signature signs
116  *        this must be followed by "size - 8" bytes of
117  *        the actual signed data
118  */
119 struct GNUNET_CRYPTO_RsaSignaturePurpose
120 {
121   /**
122    * How many bytes does this signature sign?
123    * (including this purpose header); in network
124    * byte order (!).
125    */
126   uint32_t size GNUNET_PACKED;
127
128   /**
129    * What does this signature vouch for?  This
130    * must contain a GNUNET_SIGNATURE_PURPOSE_XXX
131    * constant (from gnunet_signatures.h).  In
132    * network byte order!
133    */
134   uint32_t purpose GNUNET_PACKED;
135
136 };
137
138
139 /**
140  * @brief A public key.
141  */
142 struct GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
143 {
144   /**
145    * In big-endian, must be GNUNET_CRYPTO_RSA_KEY_LENGTH+4
146    */
147   uint16_t len GNUNET_PACKED;
148
149   /**
150    * Size of n in key; in big-endian!
151    */
152   uint16_t sizen GNUNET_PACKED;
153
154   /**
155    * The key itself, contains n followed by e.
156    */
157   unsigned char key[GNUNET_CRYPTO_RSA_KEY_LENGTH];
158
159   /**
160    * Padding (must be 0)
161    */
162   uint16_t padding GNUNET_PACKED;
163 };
164
165
166 /**
167  * RSA Encrypted data.
168  */
169 struct GNUNET_CRYPTO_RsaEncryptedData
170 {
171   unsigned char encoding[GNUNET_CRYPTO_RSA_DATA_ENCODING_LENGTH];
172 };
173
174
175 /**
176  * @brief type for session keys
177  */
178 struct GNUNET_CRYPTO_AesSessionKey
179 {
180   /**
181    * Actual key.
182    */
183   unsigned char key[GNUNET_CRYPTO_AES_KEY_LENGTH];
184
185   /**
186    * checksum!
187    */
188   uint32_t crc32 GNUNET_PACKED;
189 };
190
191
192 /**
193  * @brief IV for sym cipher
194  *
195  * NOTE: must be smaller (!) in size than the
196  * GNUNET_HashCode.
197  */
198 struct GNUNET_CRYPTO_AesInitializationVector
199 {
200   unsigned char iv[GNUNET_CRYPTO_AES_KEY_LENGTH / 2];
201 };
202
203
204 /* **************** Functions and Macros ************* */
205
206
207 /**
208  * Compute the CRC32 checksum for the first len
209  * bytes of the buffer.
210  *
211  * @param buf the data over which we're taking the CRC
212  * @param len the length of the buffer in bytes
213  * @return the resulting CRC32 checksum
214  */
215 int32_t GNUNET_CRYPTO_crc32_n (const void *buf, 
216                                size_t len);
217
218
219 /**
220  * Produce a random value.
221  *
222  * @param mode desired quality of the random number
223  * @param i the upper limit (exclusive) for the random number
224  * @return a random value in the interval [0,i) (exclusive).
225  */
226 uint32_t GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality mode,
227                                    uint32_t i);
228
229
230 /**
231  * Random on unsigned 64-bit values. 
232  *
233  * @param mode desired quality of the random number
234  * @param max value returned will be in range [0,max) (exclusive)
235  * @return random 64-bit number
236  */
237 uint64_t GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode,
238                                    uint64_t max);
239
240
241 /**
242  * Get an array with a random permutation of the
243  * numbers 0...n-1.
244  * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
245  * @param n the size of the array
246  * @return the permutation array (allocated from heap)
247  */
248 unsigned int *GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
249                                             unsigned int n);
250
251
252 /**
253  * Create a new Session key.
254  *
255  * @param key key to initialize
256  */
257 void GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey
258                                            *key);
259
260
261 /**
262  * Check that a new session key is well-formed.
263  *
264  * @param key key to check
265  * @return GNUNET_OK if the key is valid
266  */
267 int GNUNET_CRYPTO_aes_check_session_key (const struct
268                                          GNUNET_CRYPTO_AesSessionKey *key);
269
270
271 /**
272  * Encrypt a block with the public key of another
273  * host that uses the same cyper.
274  *
275  * @param block the block to encrypt
276  * @param len the size of the block
277  * @param sessionkey the key used to encrypt
278  * @param iv the initialization vector to use, use INITVALUE
279  *        for streams.
280  * @return the size of the encrypted block, -1 for errors
281  */
282 ssize_t GNUNET_CRYPTO_aes_encrypt (const void *block,
283                                    size_t len,
284                                    const struct GNUNET_CRYPTO_AesSessionKey
285                                    *sessionkey,
286                                    const struct
287                                    GNUNET_CRYPTO_AesInitializationVector *iv,
288                                    void *result);
289
290
291 /**
292  * Decrypt a given block with the sessionkey.
293  *
294  * @param block the data to decrypt, encoded as returned by encrypt
295  * @param size how big is the block?
296  * @param sessionkey the key used to decrypt
297  * @param iv the initialization vector to use
298  * @param result address to store the result at
299  * @return -1 on failure, size of decrypted block on success
300  */
301 ssize_t GNUNET_CRYPTO_aes_decrypt (const void *block, 
302                                    size_t size,
303                                    const struct GNUNET_CRYPTO_AesSessionKey *sessionkey, 
304                                    const struct GNUNET_CRYPTO_AesInitializationVector *iv,
305                                    void *result);
306
307
308 /**
309  * Convert hash to ASCII encoding.
310  * @param block the hash code
311  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
312  *  safely cast to char*, a '\\0' termination is set).
313  */
314 void GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
315                                 struct GNUNET_CRYPTO_HashAsciiEncoded
316                                 *result);
317
318
319 /**
320  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
321  * @param enc the encoding
322  * @param result where to store the GNUNET_CRYPTO_hash code
323  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
324  */
325 int GNUNET_CRYPTO_hash_from_string (const char *enc,
326                                     GNUNET_HashCode * result);
327
328
329 /**
330  * Compute the distance between 2 hashcodes.
331  * The computation must be fast, not involve
332  * a.a or a.e (they're used elsewhere), and
333  * be somewhat consistent. And of course, the
334  * result should be a positive number.
335  *
336  * @param a some hash code
337  * @param b some hash code
338  * @return number between 0 and 65536
339  */
340 uint32_t GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
341                                           const GNUNET_HashCode * b);
342
343
344 /**
345  * Compute hash of a given block.
346  *
347  * @param block the data to hash
348  * @param size size of the block
349  * @param ret pointer to where to write the hashcode
350  */
351 void GNUNET_CRYPTO_hash (const void *block, 
352                          size_t size,
353                          GNUNET_HashCode * ret);
354
355
356 /**
357  * Function called once the hash computation over the
358  * specified file has completed.
359  *
360  * @param cls closure
361  * @param res resulting hash, NULL on error
362  */
363 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
364                                                      const GNUNET_HashCode *
365                                                      res);
366
367
368 /**
369  * Handle to file hashing operation.
370  */
371 struct GNUNET_CRYPTO_FileHashContext;
372
373 /**
374  * Compute the hash of an entire file.
375  *
376  * @param sched scheduler to use
377  * @param priority scheduling priority to use
378  * @param filename name of file to hash
379  * @param blocksize number of bytes to process in one task
380  * @param callback function to call upon completion
381  * @param callback_cls closure for callback
382  * @return NULL on (immediate) errror
383  */
384 struct GNUNET_CRYPTO_FileHashContext *
385 GNUNET_CRYPTO_hash_file (struct GNUNET_SCHEDULER_Handle *sched,
386                          enum GNUNET_SCHEDULER_Priority priority,
387                          const char *filename,
388                          size_t blocksize,
389                          GNUNET_CRYPTO_HashCompletedCallback callback,
390                          void *callback_cls);
391
392
393 /**
394  * Cancel a file hashing operation.
395  *
396  * @param fhc operation to cancel (callback must not yet have been invoked)
397  */
398 void
399 GNUNET_CRYPTO_hash_file_cancel (struct GNUNET_CRYPTO_FileHashContext *fhc);
400
401
402 /**
403  * Create a random hash code.
404  *
405  * @param mode desired quality level
406  * @param result hash code that is randomized
407  */
408 void GNUNET_CRYPTO_hash_create_random (enum GNUNET_CRYPTO_Quality mode,
409                                        GNUNET_HashCode * result);
410
411
412 /**
413  * compute result(delta) = b - a
414  *
415  * @param a some hash code
416  * @param b some hash code
417  * @param result set to b - a 
418  */
419 void GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
420                                     const GNUNET_HashCode * b,
421                                     GNUNET_HashCode * result);
422
423
424 /**
425  * compute result(b) = a + delta
426  *
427  * @param a some hash code
428  * @param delta some hash code
429  * @param result set to a + delta
430  */
431 void GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
432                              const GNUNET_HashCode * delta,
433                              GNUNET_HashCode * result);
434
435
436 /**
437  * compute result = a ^ b
438  *
439  * @param a some hash code
440  * @param b some hash code
441  * @param result set to a ^ b 
442  */
443 void GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
444                              const GNUNET_HashCode * b,
445                              GNUNET_HashCode * result);
446
447
448 /**
449  * Convert a hashcode into a key.
450  *
451  * @param hc hash code that serves to generate the key
452  * @param skey set to a valid session key
453  * @param iv set to a valid initialization vector
454  */
455 void GNUNET_CRYPTO_hash_to_aes_key (const GNUNET_HashCode * hc,
456                                     struct GNUNET_CRYPTO_AesSessionKey *skey,
457                                     struct
458                                     GNUNET_CRYPTO_AesInitializationVector
459                                     *iv);
460
461
462 /**
463  * Obtain a bit from a hashcode.
464  *
465  * @param code the GNUNET_CRYPTO_hash to index bit-wise
466  * @param bit index into the hashcode, [0...159]
467  * @return Bit \a bit from hashcode \a code, -1 for invalid index
468  */
469 int GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code,
470                                 unsigned int bit);
471
472
473 /**
474  * Compare function for HashCodes, producing a total ordering
475  * of all hashcodes.
476  *
477  * @param h1 some hash code
478  * @param h2 some hash code
479  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
480  */
481 int GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
482                             const GNUNET_HashCode * h2);
483
484
485 /**
486  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
487  * in the XOR metric (Kademlia).
488  *
489  * @param h1 some hash code
490  * @param h2 some hash code
491  * @param target some hash code
492  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
493  */
494 int GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
495                                const GNUNET_HashCode * h2,
496                                const GNUNET_HashCode * target);
497
498
499 /**
500  * Create a new private key. Caller must free return value.
501  *
502  * @return fresh private key
503  */
504 struct GNUNET_CRYPTO_RsaPrivateKey *GNUNET_CRYPTO_rsa_key_create (void);
505
506
507 /**
508  * Create a new private key by reading it from a file.  If the
509  * files does not exist, create a new key and write it to the
510  * file.  Caller must free return value. Note that this function
511  * can not guarantee that another process might not be trying
512  * the same operation on the same file at the same time.  The
513  * caller must somehow know that the file either already exists
514  * with a valid key OR be sure that no other process is calling
515  * this function at the same time.  If the contents of the file
516  * are invalid the old file is deleted and a fresh key is
517  * created.
518  *
519  * @param filename name of file to use for storage
520  * @return new private key, NULL on error (for example,
521  *   permission denied)
522  */
523 struct GNUNET_CRYPTO_RsaPrivateKey
524   *GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
525
526
527 /**
528  * Deterministically (!) create a private key using only the
529  * given HashCode as input to the PRNG.
530  *
531  * @param hc "random" input to PRNG
532  * @return some private key purely dependent on input
533  */
534 struct GNUNET_CRYPTO_RsaPrivateKey
535   *GNUNET_CRYPTO_rsa_key_create_from_hash (const GNUNET_HashCode * hc);
536
537
538 /**
539  * Free memory occupied by the private key.
540  * @param hostkey pointer to the memory to free
541  */
542 void GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
543
544
545 /**
546  * Extract the public key of the host.
547  *
548  * @param priv the private key
549  * @param pub where to write the public key
550  */
551 void GNUNET_CRYPTO_rsa_key_get_public (const struct
552                                        GNUNET_CRYPTO_RsaPrivateKey *priv,
553                                        struct
554                                        GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
555                                        *pub);
556
557
558 /**
559  * Encrypt a block with the public key of another host that uses the
560  * same cyper.
561  *
562  * @param block the block to encrypt
563  * @param size the size of block
564  * @param publicKey the encoded public key used to encrypt
565  * @param target where to store the encrypted block
566  * @return GNUNET_SYSERR on error, GNUNET_OK if ok
567  */
568 int GNUNET_CRYPTO_rsa_encrypt (const void *block,
569                                size_t size,
570                                const struct
571                                GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
572                                *publicKey,
573                                struct GNUNET_CRYPTO_RsaEncryptedData *target);
574
575
576 /**
577  * Decrypt a given block with the hostkey.
578  *
579  * @param key the key to use
580  * @param block the data to decrypt, encoded as returned by encrypt, not consumed
581  * @param result pointer to a location where the result can be stored
582  * @param max how many bytes of a result are expected? Must be exact.
583  * @return the size of the decrypted block (that is, size) or -1 on error
584  */
585 ssize_t GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
586                                    const struct GNUNET_CRYPTO_RsaEncryptedData
587                                    *block,
588                                    void *result, 
589                                    size_t max);
590
591
592 /**
593  * Sign a given block.
594  *
595  * @param key private key to use for the signing
596  * @param purpose what to sign (size, purpose)
597  * @param sig where to write the signature
598  * @return GNUNET_SYSERR on error, GNUNET_OK on success
599  */
600 int GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
601                             const struct GNUNET_CRYPTO_RsaSignaturePurpose
602                             *purpose,
603                             struct GNUNET_CRYPTO_RsaSignature *sig);
604
605
606 /**
607  * Verify signature.  Note that the caller MUST have already
608  * checked that "validate->size" bytes are actually available.
609  *
610  * @param purpose what is the purpose that validate should have?
611  * @param validate block to validate (size, purpose, data)
612  * @param sig signature that is being validated
613  * @param publicKey public key of the signer
614  * @return GNUNET_OK if ok, GNUNET_SYSERR if invalid
615  */
616 int GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
617                               const struct GNUNET_CRYPTO_RsaSignaturePurpose
618                               *validate,
619                               const struct GNUNET_CRYPTO_RsaSignature *sig,
620                               const struct
621                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
622                               *publicKey);
623
624
625
626 /**
627  * This function should only be called in testcases
628  * where strong entropy gathering is not desired
629  * (for example, for hostkey generation). 
630  */
631 void GNUNET_CRYPTO_random_disable_entropy_gathering (void);
632
633 #if 0                           /* keep Emacsens' auto-indent happy */
634 {
635 #endif
636 #ifdef __cplusplus
637 }
638 #endif
639
640
641 /* ifndef GNUNET_CRYPTO_LIB_H */
642 #endif
643 /* end of gnunet_crypto_lib.h */