ng
[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 int GNUNET_CRYPTO_crc32_n (const void *buf, unsigned int len);
206
207
208 /**
209  * Produce a random value.
210  *
211  * @param i the upper limit (exclusive) for the random number
212  * @return a random value in the interval [0,i[.
213  */
214 unsigned int GNUNET_CRYPTO_random_u32 (enum GNUNET_CRYPTO_Quality,
215                                        unsigned int i);
216
217
218 /**
219  * Random on unsigned 64-bit values.  We break them down into signed
220  * 32-bit values and reassemble the 64-bit random value bit-wise.
221  */
222 unsigned long long GNUNET_CRYPTO_random_u64 (enum GNUNET_CRYPTO_Quality mode,
223                                              unsigned long long u);
224
225
226 /**
227  * Get an array with a random permutation of the
228  * numbers 0...n-1.
229  * @param mode GNUNET_CRYPTO_QUALITY_STRONG if the strong (but expensive) PRNG should be used, GNUNET_CRYPTO_QUALITY_WEAK otherwise
230  * @param n the size of the array
231  * @return the permutation array (allocated from heap)
232  */
233 unsigned int *GNUNET_CRYPTO_random_permute (enum GNUNET_CRYPTO_Quality mode,
234                                             unsigned int n);
235
236
237 /**
238  * Create a new Session key.
239  */
240 void GNUNET_CRYPTO_aes_create_session_key (struct GNUNET_CRYPTO_AesSessionKey
241                                            *key);
242
243
244 /**
245  * Check that a new session key is well-formed.
246  *
247  * @return GNUNET_OK if the key is valid
248  */
249 int GNUNET_CRYPTO_aes_check_session_key (const struct
250                                          GNUNET_CRYPTO_AesSessionKey *key);
251
252
253 /**
254  * Encrypt a block with the public key of another
255  * host that uses the same cyper.
256  *
257  * @param block the block to encrypt
258  * @param len the size of the block
259  * @param sessionkey the key used to encrypt
260  * @param iv the initialization vector to use, use INITVALUE
261  *        for streams.
262  * @returns the size of the encrypted block, -1 for errors
263  */
264 int GNUNET_CRYPTO_aes_encrypt (const void *block,
265                                uint16_t len,
266                                const struct GNUNET_CRYPTO_AesSessionKey
267                                *sessionkey,
268                                const struct
269                                GNUNET_CRYPTO_AesInitializationVector *iv,
270                                void *result);
271
272
273 /**
274  * Decrypt a given block with the sessionkey.
275  *
276  * @param sessionkey the key used to decrypt
277  * @param block the data to decrypt, encoded as returned by encrypt
278  * @param size how big is the block?
279  * @param iv the initialization vector to use
280  * @param result address to store the result at
281  * @return -1 on failure, size of decrypted block on success
282  */
283 int GNUNET_CRYPTO_aes_decrypt (const struct GNUNET_CRYPTO_AesSessionKey
284                                *sessionkey, const void *block, uint16_t size,
285                                const struct
286                                GNUNET_CRYPTO_AesInitializationVector *iv,
287                                void *result);
288
289
290 /**
291  * Convert GNUNET_CRYPTO_hash to ASCII encoding.
292  * @param block the GNUNET_CRYPTO_hash code
293  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
294  *  safely cast to char*, a '\0' termination is set).
295  */
296 void GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
297                                 struct GNUNET_CRYPTO_HashAsciiEncoded
298                                 *result);
299
300
301 /**
302  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
303  * @param enc the encoding
304  * @param result where to store the GNUNET_CRYPTO_hash code
305  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
306  */
307 int GNUNET_CRYPTO_hash_from_string (const char *enc,
308                                     GNUNET_HashCode * result);
309
310
311 /**
312  * Compute the distance between 2 hashcodes.
313  * The computation must be fast, not involve
314  * a.a or a.e (they're used elsewhere), and
315  * be somewhat consistent. And of course, the
316  * result should be a positive number.
317  * @return number between 0 and 65536
318  */
319 unsigned int GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
320                                               const GNUNET_HashCode * b);
321
322
323 /**
324  * Hash block of given size.
325  * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
326  * @param ret pointer to where to write the hashcode
327  */
328 void GNUNET_CRYPTO_hash (const void *block, unsigned int size,
329                          GNUNET_HashCode * ret);
330
331
332 /**
333  * Function called once the hash computation over the
334  * specified file has completed.
335  *
336  * @param cls closure
337  * @param res resulting hash, NULL on error
338  */
339 typedef void (*GNUNET_CRYPTO_HashCompletedCallback) (void *cls,
340                                                      const GNUNET_HashCode *
341                                                      res);
342
343
344 /**
345  * Compute the hash of an entire file.
346  *
347  * @param sched scheduler to use
348  * @param priority scheduling priority to use
349  * @param run_on_shutdown should we complete even on shutdown?
350  * @param filename name of file to hash
351  * @param blocksize number of bytes to process in one task
352  * @param callback function to call upon completion
353  * @param callback_cls closure for callback
354  */
355 void GNUNET_CRYPTO_hash_file (struct GNUNET_SCHEDULER_Handle *sched,
356                               enum GNUNET_SCHEDULER_Priority priority,
357                               int run_on_shutdown,
358                               const char *filename,
359                               size_t blocksize,
360                               GNUNET_CRYPTO_HashCompletedCallback callback,
361                               void *callback_cls);
362
363
364 /**
365  * Create a random hash code.
366  */
367 void GNUNET_CRYPTO_hash_create_random (GNUNET_HashCode * result);
368
369
370 /**
371  * compute result(delta) = b - a
372  */
373 void GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
374                                     const GNUNET_HashCode * b,
375                                     GNUNET_HashCode * result);
376
377
378 /**
379  * compute result(b) = a + delta
380  */
381 void GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
382                              const GNUNET_HashCode * delta,
383                              GNUNET_HashCode * result);
384
385
386 /**
387  * compute result = a ^ b
388  */
389 void GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
390                              const GNUNET_HashCode * b,
391                              GNUNET_HashCode * result);
392
393
394 /**
395  * Convert a hashcode into a key.
396  */
397 void GNUNET_CRYPTO_hash_to_AES_key (const GNUNET_HashCode * hc,
398                                     struct GNUNET_CRYPTO_AesSessionKey *skey,
399                                     struct
400                                     GNUNET_CRYPTO_AesInitializationVector
401                                     *iv);
402
403
404 /**
405  * Obtain a bit from a hashcode.
406  * @param code the GNUNET_CRYPTO_hash to index bit-wise
407  * @param bit index into the hashcode, [0...159]
408  * @return Bit \a bit from hashcode \a code, -1 for invalid index
409  */
410 int GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code,
411                                 unsigned int bit);
412
413
414 /**
415  * Compare function for HashCodes, producing a total ordering
416  * of all hashcodes.
417  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
418  */
419 int GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
420                             const GNUNET_HashCode * h2);
421
422
423 /**
424  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
425  * in the XOR metric (Kademlia).
426  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
427  */
428 int GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
429                                const GNUNET_HashCode * h2,
430                                const GNUNET_HashCode * target);
431
432
433 /**
434  * Create a new private key. Caller must free return value.
435  */
436 struct GNUNET_CRYPTO_RsaPrivateKey *GNUNET_CRYPTO_rsa_key_create (void);
437
438
439 /**
440  * Create a new private key by reading it from a file.  If the
441  * files does not exist, create a new key and write it to the
442  * file.  Caller must free return value. Note that this function
443  * can not guarantee that another process might not be trying
444  * the same operation on the same file at the same time.  The
445  * caller must somehow know that the file either already exists
446  * with a valid key OR be sure that no other process is calling
447  * this function at the same time.  If the contents of the file
448  * are invalid the old file is deleted and a fresh key is
449  * created.
450  *
451  * @return new private key, NULL on error (for example,
452  *   permission denied)
453  */
454 struct GNUNET_CRYPTO_RsaPrivateKey
455   *GNUNET_CRYPTO_rsa_key_create_from_file (const char *filename);
456
457
458 /**
459  * Deterministically (!) create a private key using only the
460  * given HashCode as input to the PRNG.
461  */
462 struct GNUNET_CRYPTO_RsaPrivateKey
463   *GNUNET_CRYPTO_rsa_key_create_from_hash (const GNUNET_HashCode * input);
464
465
466 /**
467  * Free memory occupied by the private key.
468  * @param hostkey pointer to the memory to free
469  */
470 void GNUNET_CRYPTO_rsa_key_free (struct GNUNET_CRYPTO_RsaPrivateKey *hostkey);
471
472
473 /**
474  * Extract the public key of the host.
475  * @param result where to write the result.
476  */
477 void GNUNET_CRYPTO_rsa_key_get_public (const struct
478                                        GNUNET_CRYPTO_RsaPrivateKey *hostkey,
479                                        struct
480                                        GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
481                                        *result);
482
483
484 /**
485  * Encrypt a block with the public key of another host that uses the
486  * same cyper.
487  *
488  * @param block the block to encrypt
489  * @param size the size of block
490  * @param publicKey the encoded public key used to encrypt
491  * @param target where to store the encrypted block
492  * @returns GNUNET_SYSERR on error, GNUNET_OK if ok
493  */
494 int GNUNET_CRYPTO_rsa_encrypt (const void *block,
495                                uint16_t size,
496                                const struct
497                                GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
498                                *publicKey,
499                                struct GNUNET_CRYPTO_RsaEncryptedData *target);
500
501
502 /**
503  * Decrypt a given block with the hostkey.
504  *
505  * @param key the key to use
506  * @param block the data to decrypt, encoded as returned by encrypt, not consumed
507  * @param result pointer to a location where the result can be stored
508  * @param size how many bytes of a result are expected? Must be exact.
509  * @returns the size of the decrypted block (that is, size) or -1 on error
510  */
511 int GNUNET_CRYPTO_rsa_decrypt (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
512                                const struct GNUNET_CRYPTO_RsaEncryptedData
513                                *block, void *result, uint16_t size);
514
515
516 /**
517  * Sign a given block.
518  *
519  * @param key private key to use for the signing
520  * @param purpose what to sign (size, purpose)
521  * @param result where to write the signature
522  * @return GNUNET_SYSERR on error, GNUNET_OK on success
523  */
524 int GNUNET_CRYPTO_rsa_sign (const struct GNUNET_CRYPTO_RsaPrivateKey *key,
525                             const struct GNUNET_CRYPTO_RsaSignaturePurpose
526                             *purpose,
527                             struct GNUNET_CRYPTO_RsaSignature *result);
528
529
530 /**
531  * Verify signature.  Note that the caller MUST have already
532  * checked that "validate->size" bytes are actually available.
533  *
534  * @param purpose what is the purpose that validate should have?
535  * @param validate block to validate (size, purpose, data)
536  * @param sig signature that is being validated
537  * @param publicKey public key of the signer
538  * @returns GNUNET_OK if ok, GNUNET_SYSERR if invalid
539  */
540 int GNUNET_CRYPTO_rsa_verify (uint32_t purpose,
541                               const struct GNUNET_CRYPTO_RsaSignaturePurpose
542                               *validate,
543                               const struct GNUNET_CRYPTO_RsaSignature *sig,
544                               const struct
545                               GNUNET_CRYPTO_RsaPublicKeyBinaryEncoded
546                               *publicKey);
547
548
549
550 /**
551  * This function should only be called in testcases
552  * where strong entropy gathering is not desired
553  * (for example, for hostkey generation).
554  */
555 void GNUNET_CRYPTO_random_disable_entropy_gathering (void);
556
557 #if 0                           /* keep Emacsens' auto-indent happy */
558 {
559 #endif
560 #ifdef __cplusplus
561 }
562 #endif
563
564
565 /* ifndef GNUNET_CRYPTO_LIB_H */
566 #endif
567 /* end of gnunet_crypto_lib.h */