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