GNUNET_IO_handle => GNUNET_DISK_handle
[oweals/gnunet.git] / src / util / crypto_hash.c
1 /*
2      This file is part of GNUnet.
3      (C) 2001, 2002, 2003, 2004, 2005, 2006, 2009 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      SHA-512 code by Jean-Luc Cooke <jlcooke@certainkey.com>
21
22      Copyright (c) Jean-Luc Cooke <jlcooke@certainkey.com>
23      Copyright (c) Andrew McDonald <andrew@mcdonald.org.uk>
24      Copyright (c) 2003 Kyle McMartin <kyle@debian.org>
25 */
26
27 /**
28  * @file util/crypto_hash.c
29  * @brief SHA-512 GNUNET_CRYPTO_hash related functions
30  * @author Christian Grothoff
31  */
32
33 #include "platform.h"
34 #include "gnunet_common.h"
35 #include "gnunet_crypto_lib.h"
36 #include "gnunet_disk_lib.h"
37
38 #define SHA512_DIGEST_SIZE 64
39 #define SHA512_HMAC_BLOCK_SIZE 128
40
41 struct sha512_ctx
42 {
43   unsigned long long state[8];
44   unsigned int count[4];
45   unsigned char buf[128];
46 };
47
48 static unsigned long long
49 Ch (unsigned long long x, unsigned long long y, unsigned long long z)
50 {
51   return z ^ (x & (y ^ z));
52 }
53
54 static unsigned long long
55 Maj (unsigned long long x, unsigned long long y, unsigned long long z)
56 {
57   return (x & y) | (z & (x | y));
58 }
59
60 static unsigned long long
61 RORu64 (unsigned long long x, unsigned long long y)
62 {
63   return (x >> y) | (x << (64 - y));
64 }
65
66 const unsigned long long sha512_K[80] = {
67   0x428a2f98d728ae22ULL, 0x7137449123ef65cdULL, 0xb5c0fbcfec4d3b2fULL,
68   0xe9b5dba58189dbbcULL, 0x3956c25bf348b538ULL, 0x59f111f1b605d019ULL,
69   0x923f82a4af194f9bULL, 0xab1c5ed5da6d8118ULL, 0xd807aa98a3030242ULL,
70   0x12835b0145706fbeULL, 0x243185be4ee4b28cULL, 0x550c7dc3d5ffb4e2ULL,
71   0x72be5d74f27b896fULL, 0x80deb1fe3b1696b1ULL, 0x9bdc06a725c71235ULL,
72   0xc19bf174cf692694ULL, 0xe49b69c19ef14ad2ULL, 0xefbe4786384f25e3ULL,
73   0x0fc19dc68b8cd5b5ULL, 0x240ca1cc77ac9c65ULL, 0x2de92c6f592b0275ULL,
74   0x4a7484aa6ea6e483ULL, 0x5cb0a9dcbd41fbd4ULL, 0x76f988da831153b5ULL,
75   0x983e5152ee66dfabULL, 0xa831c66d2db43210ULL, 0xb00327c898fb213fULL,
76   0xbf597fc7beef0ee4ULL, 0xc6e00bf33da88fc2ULL, 0xd5a79147930aa725ULL,
77   0x06ca6351e003826fULL, 0x142929670a0e6e70ULL, 0x27b70a8546d22ffcULL,
78   0x2e1b21385c26c926ULL, 0x4d2c6dfc5ac42aedULL, 0x53380d139d95b3dfULL,
79   0x650a73548baf63deULL, 0x766a0abb3c77b2a8ULL, 0x81c2c92e47edaee6ULL,
80   0x92722c851482353bULL, 0xa2bfe8a14cf10364ULL, 0xa81a664bbc423001ULL,
81   0xc24b8b70d0f89791ULL, 0xc76c51a30654be30ULL, 0xd192e819d6ef5218ULL,
82   0xd69906245565a910ULL, 0xf40e35855771202aULL, 0x106aa07032bbd1b8ULL,
83   0x19a4c116b8d2d0c8ULL, 0x1e376c085141ab53ULL, 0x2748774cdf8eeb99ULL,
84   0x34b0bcb5e19b48a8ULL, 0x391c0cb3c5c95a63ULL, 0x4ed8aa4ae3418acbULL,
85   0x5b9cca4f7763e373ULL, 0x682e6ff3d6b2b8a3ULL, 0x748f82ee5defb2fcULL,
86   0x78a5636f43172f60ULL, 0x84c87814a1f0ab72ULL, 0x8cc702081a6439ecULL,
87   0x90befffa23631e28ULL, 0xa4506cebde82bde9ULL, 0xbef9a3f7b2c67915ULL,
88   0xc67178f2e372532bULL, 0xca273eceea26619cULL, 0xd186b8c721c0c207ULL,
89   0xeada7dd6cde0eb1eULL, 0xf57d4f7fee6ed178ULL, 0x06f067aa72176fbaULL,
90   0x0a637dc5a2c898a6ULL, 0x113f9804bef90daeULL, 0x1b710b35131c471bULL,
91   0x28db77f523047d84ULL, 0x32caab7b40c72493ULL, 0x3c9ebe0a15c9bebcULL,
92   0x431d67c49c100d4cULL, 0x4cc5d4becb3e42b6ULL, 0x597f299cfc657e2aULL,
93   0x5fcb6fab3ad6faecULL, 0x6c44198c4a475817ULL,
94 };
95
96 #define e0(x)       (RORu64(x,28) ^ RORu64(x,34) ^ RORu64(x,39))
97 #define e1(x)       (RORu64(x,14) ^ RORu64(x,18) ^ RORu64(x,41))
98 #define s0(x)       (RORu64(x, 1) ^ RORu64(x, 8) ^ (x >> 7))
99 #define s1(x)       (RORu64(x,19) ^ RORu64(x,61) ^ (x >> 6))
100
101 /* H* initial state for SHA-512 */
102 #define H0         0x6a09e667f3bcc908ULL
103 #define H1         0xbb67ae8584caa73bULL
104 #define H2         0x3c6ef372fe94f82bULL
105 #define H3         0xa54ff53a5f1d36f1ULL
106 #define H4         0x510e527fade682d1ULL
107 #define H5         0x9b05688c2b3e6c1fULL
108 #define H6         0x1f83d9abfb41bd6bULL
109 #define H7         0x5be0cd19137e2179ULL
110
111 /* H'* initial state for SHA-384 */
112 #define HP0 0xcbbb9d5dc1059ed8ULL
113 #define HP1 0x629a292a367cd507ULL
114 #define HP2 0x9159015a3070dd17ULL
115 #define HP3 0x152fecd8f70e5939ULL
116 #define HP4 0x67332667ffc00b31ULL
117 #define HP5 0x8eb44a8768581511ULL
118 #define HP6 0xdb0c2e0d64f98fa7ULL
119 #define HP7 0x47b5481dbefa4fa4ULL
120
121 #define LOAD_OP(t1, I, W, input) \
122   t1  = input[(8*I)  ] & 0xff;\
123   t1 <<= 8;\
124   t1 |= input[(8*I)+1] & 0xff;\
125   t1 <<= 8;\
126   t1 |= input[(8*I)+2] & 0xff;\
127   t1 <<= 8;\
128   t1 |= input[(8*I)+3] & 0xff;\
129   t1 <<= 8;\
130   t1 |= input[(8*I)+4] & 0xff;\
131   t1 <<= 8;\
132   t1 |= input[(8*I)+5] & 0xff;\
133   t1 <<= 8;\
134   t1 |= input[(8*I)+6] & 0xff;\
135   t1 <<= 8;\
136   t1 |= input[(8*I)+7] & 0xff;\
137   W[I] = t1;
138
139
140 #define BLEND_OP(I, W) \
141   W[I] = s1(W[I-2]) + W[I-7] + s0(W[I-15]) + W[I-16];
142
143 static void
144 sha512_transform (unsigned long long *state, const unsigned char *input)
145 {
146   unsigned long long a, b, c, d, e, f, g, h, t1, t2;
147   unsigned long long W[80];
148   unsigned long long t0;
149   int i;
150
151   /* load the input */
152   for (i = 0; i < 16; i++)
153     {
154       LOAD_OP (t0, i, W, input);
155     }
156
157   for (i = 16; i < 80; i++)
158     {
159       BLEND_OP (i, W);
160     }
161
162   /* load the state into our registers */
163   a = state[0];
164   b = state[1];
165   c = state[2];
166   d = state[3];
167   e = state[4];
168   f = state[5];
169   g = state[6];
170   h = state[7];
171
172   /* now iterate */
173   for (i = 0; i < 80; i += 8)
174     {
175       t1 = h + e1 (e) + Ch (e, f, g) + sha512_K[i] + W[i];
176       t2 = e0 (a) + Maj (a, b, c);
177       d += t1;
178       h = t1 + t2;
179       t1 = g + e1 (d) + Ch (d, e, f) + sha512_K[i + 1] + W[i + 1];
180       t2 = e0 (h) + Maj (h, a, b);
181       c += t1;
182       g = t1 + t2;
183       t1 = f + e1 (c) + Ch (c, d, e) + sha512_K[i + 2] + W[i + 2];
184       t2 = e0 (g) + Maj (g, h, a);
185       b += t1;
186       f = t1 + t2;
187       t1 = e + e1 (b) + Ch (b, c, d) + sha512_K[i + 3] + W[i + 3];
188       t2 = e0 (f) + Maj (f, g, h);
189       a += t1;
190       e = t1 + t2;
191       t1 = d + e1 (a) + Ch (a, b, c) + sha512_K[i + 4] + W[i + 4];
192       t2 = e0 (e) + Maj (e, f, g);
193       h += t1;
194       d = t1 + t2;
195       t1 = c + e1 (h) + Ch (h, a, b) + sha512_K[i + 5] + W[i + 5];
196       t2 = e0 (d) + Maj (d, e, f);
197       g += t1;
198       c = t1 + t2;
199       t1 = b + e1 (g) + Ch (g, h, a) + sha512_K[i + 6] + W[i + 6];
200       t2 = e0 (c) + Maj (c, d, e);
201       f += t1;
202       b = t1 + t2;
203       t1 = a + e1 (f) + Ch (f, g, h) + sha512_K[i + 7] + W[i + 7];
204       t2 = e0 (b) + Maj (b, c, d);
205       e += t1;
206       a = t1 + t2;
207     }
208
209   state[0] += a;
210   state[1] += b;
211   state[2] += c;
212   state[3] += d;
213   state[4] += e;
214   state[5] += f;
215   state[6] += g;
216   state[7] += h;
217
218   /* erase our data */
219   a = b = c = d = e = f = g = h = t1 = t2 = 0;
220   memset (W, 0, 80 * sizeof (unsigned long long));
221 }
222
223 static void
224 sha512_init (struct sha512_ctx *sctx)
225 {
226   sctx->state[0] = H0;
227   sctx->state[1] = H1;
228   sctx->state[2] = H2;
229   sctx->state[3] = H3;
230   sctx->state[4] = H4;
231   sctx->state[5] = H5;
232   sctx->state[6] = H6;
233   sctx->state[7] = H7;
234   sctx->count[0] = sctx->count[1] = sctx->count[2] = sctx->count[3] = 0;
235   memset (sctx->buf, 0, sizeof (sctx->buf));
236 }
237
238 static void
239 sha512_update (struct sha512_ctx *sctx,
240                const unsigned char *data, unsigned int len)
241 {
242   unsigned int i, index, part_len;
243
244   /* Compute number of bytes mod 128 */
245   index = (unsigned int) ((sctx->count[0] >> 3) & 0x7F);
246
247   /* Update number of bits */
248   if ((sctx->count[0] += (len << 3)) < (len << 3))
249     {
250       if ((sctx->count[1] += 1) < 1)
251         if ((sctx->count[2] += 1) < 1)
252           sctx->count[3]++;
253       sctx->count[1] += (len >> 29);
254     }
255
256   part_len = 128 - index;
257
258   /* Transform as many times as possible. */
259   if (len >= part_len)
260     {
261       memcpy (&sctx->buf[index], data, part_len);
262       sha512_transform (sctx->state, sctx->buf);
263
264       for (i = part_len; i + 127 < len; i += 128)
265         sha512_transform (sctx->state, &data[i]);
266
267       index = 0;
268     }
269   else
270     {
271       i = 0;
272     }
273
274   /* Buffer remaining input */
275   memcpy (&sctx->buf[index], &data[i], len - i);
276 }
277
278 static void
279 sha512_final (struct sha512_ctx *sctx, unsigned char *hash)
280 {
281   static unsigned char padding[128] = { 0x80, };
282
283   unsigned int t;
284   unsigned long long t2;
285   unsigned char bits[128];
286   unsigned int index, pad_len;
287   int i, j;
288
289   index = pad_len = t = i = j = 0;
290   t2 = 0;
291
292   /* Save number of bits */
293   t = sctx->count[0];
294   bits[15] = t;
295   t >>= 8;
296   bits[14] = t;
297   t >>= 8;
298   bits[13] = t;
299   t >>= 8;
300   bits[12] = t;
301   t = sctx->count[1];
302   bits[11] = t;
303   t >>= 8;
304   bits[10] = t;
305   t >>= 8;
306   bits[9] = t;
307   t >>= 8;
308   bits[8] = t;
309   t = sctx->count[2];
310   bits[7] = t;
311   t >>= 8;
312   bits[6] = t;
313   t >>= 8;
314   bits[5] = t;
315   t >>= 8;
316   bits[4] = t;
317   t = sctx->count[3];
318   bits[3] = t;
319   t >>= 8;
320   bits[2] = t;
321   t >>= 8;
322   bits[1] = t;
323   t >>= 8;
324   bits[0] = t;
325
326   /* Pad out to 112 mod 128. */
327   index = (sctx->count[0] >> 3) & 0x7f;
328   pad_len = (index < 112) ? (112 - index) : ((128 + 112) - index);
329   sha512_update (sctx, padding, pad_len);
330
331   /* Append length (before padding) */
332   sha512_update (sctx, bits, 16);
333
334   /* Store state in digest */
335   for (i = j = 0; i < 8; i++, j += 8)
336     {
337       t2 = sctx->state[i];
338       hash[j + 7] = (char) t2 & 0xff;
339       t2 >>= 8;
340       hash[j + 6] = (char) t2 & 0xff;
341       t2 >>= 8;
342       hash[j + 5] = (char) t2 & 0xff;
343       t2 >>= 8;
344       hash[j + 4] = (char) t2 & 0xff;
345       t2 >>= 8;
346       hash[j + 3] = (char) t2 & 0xff;
347       t2 >>= 8;
348       hash[j + 2] = (char) t2 & 0xff;
349       t2 >>= 8;
350       hash[j + 1] = (char) t2 & 0xff;
351       t2 >>= 8;
352       hash[j] = (char) t2 & 0xff;
353     }
354
355   /* Zeroize sensitive information. */
356   memset (sctx, 0, sizeof (struct sha512_ctx));
357 }
358
359 /**
360  * Hash block of given size.
361  *
362  * @param block the data to GNUNET_CRYPTO_hash, length is given as a second argument
363  * @param size the length of the data to GNUNET_CRYPTO_hash
364  * @param ret pointer to where to write the hashcode
365  */
366 void
367 GNUNET_CRYPTO_hash (const void *block, unsigned int size,
368                     GNUNET_HashCode * ret)
369 {
370   struct sha512_ctx ctx;
371
372   sha512_init (&ctx);
373   sha512_update (&ctx, block, size);
374   sha512_final (&ctx, (unsigned char *) ret);
375 }
376
377
378 /**
379  * Context used when hashing a file.
380  */
381 struct FileHashContext
382 {
383
384   /**
385    * Function to call upon completion.
386    */
387   GNUNET_CRYPTO_HashCompletedCallback callback;
388
389   /**
390    * Closure for callback.
391    */
392   void *callback_cls;
393
394   /**
395    * IO buffer.
396    */
397   unsigned char *buffer;
398
399   /**
400    * Name of the file we are hashing.
401    */
402   char *filename;
403
404   /**
405    * Cummulated hash.
406    */
407   struct sha512_ctx hctx;
408
409   /**
410    * Blocksize.
411    */
412   size_t bsize;
413
414   /**
415    * Size of the file.
416    */
417   unsigned long long fsize;
418
419   /**
420    * Current offset.
421    */
422   unsigned long long offset;
423
424   /**
425    * Run on shutdown?
426    */
427   int run_on_shutdown;
428
429   /**
430    * File descriptor.
431    */
432   struct GNUNET_IO_Handle *fh;
433
434 };
435
436
437 /**
438  * Report result of hash computation to callback
439  * and free associated resources.
440  */
441 static void
442 file_hash_finish (struct FileHashContext *fhc, const GNUNET_HashCode * res)
443 {
444   fhc->callback (fhc->callback_cls, res);
445   GNUNET_free (fhc->filename);
446   if (!GNUNET_DISK_handle_invalid (fhc->fh))
447     GNUNET_break (0 == GNUNET_DISK_file_close (&fhc->fh));
448   GNUNET_free (fhc);            /* also frees fhc->buffer */
449 }
450
451
452 /**
453  * File hashing task.
454  *
455  * @param cls closure
456  * @param tc context
457  */
458 static void
459 file_hash_task (void *cls, const struct GNUNET_SCHEDULER_TaskContext *tc)
460 {
461   struct FileHashContext *fhc = cls;
462   GNUNET_HashCode res;
463   size_t delta;
464
465   GNUNET_assert (fhc->offset < fhc->fsize);
466   delta = fhc->bsize;
467   if (fhc->fsize - fhc->offset < delta)
468     delta = fhc->fsize - fhc->offset;
469   if (delta != GNUNET_DISK_file_read (fhc->fh, fhc->buffer, delta))
470     {
471       GNUNET_log_strerror_file (GNUNET_ERROR_TYPE_WARNING,
472                                 "read", fhc->filename);
473       file_hash_finish (fhc, NULL);
474       return;
475     }
476   sha512_update (&fhc->hctx, fhc->buffer, delta);
477   fhc->offset += delta;
478   if (fhc->offset == fhc->fsize)
479     {
480       sha512_final (&fhc->hctx, (unsigned char *) &res);
481       file_hash_finish (fhc, &res);
482       return;
483     }
484   GNUNET_SCHEDULER_add_after (tc->sched,
485                               fhc->run_on_shutdown,
486                               GNUNET_SCHEDULER_PRIORITY_KEEP,
487                               GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
488                               &file_hash_task, fhc);
489 }
490
491
492 /**
493  * Compute the hash of an entire file.
494  *
495  * @param sched scheduler to use
496  * @param priority scheduling priority to use
497  * @param run_on_shutdown should we complete even on shutdown?
498  * @param filename name of file to hash
499  * @param blocksize number of bytes to process in one task
500  * @param callback function to call upon completion
501  * @param callback_cls closure for callback
502  */
503 void
504 GNUNET_CRYPTO_hash_file (struct GNUNET_SCHEDULER_Handle *sched,
505                          enum GNUNET_SCHEDULER_Priority priority,
506                          int run_on_shutdown,
507                          const char *filename,
508                          size_t blocksize,
509                          GNUNET_CRYPTO_HashCompletedCallback callback,
510                          void *callback_cls)
511 {
512   struct FileHashContext *fhc;
513
514   GNUNET_assert (blocksize > 0);
515   fhc = GNUNET_malloc (sizeof (struct FileHashContext) + blocksize);
516   fhc->callback = callback;
517   fhc->callback_cls = callback_cls;
518   fhc->buffer = (unsigned char *) &fhc[1];
519   fhc->filename = GNUNET_strdup (filename);
520   fhc->fh = NULL;
521   sha512_init (&fhc->hctx);
522   fhc->bsize = blocksize;
523   if (GNUNET_OK != GNUNET_DISK_file_size (filename, &fhc->fsize, GNUNET_NO))
524     {
525       file_hash_finish (fhc, NULL);
526       return;
527     }
528   fhc->run_on_shutdown = run_on_shutdown;
529   fhc->fh = GNUNET_DISK_file_open (filename,
530       GNUNET_DISK_OPEN_READ);
531   if (!fhc->fh)
532     {
533       file_hash_finish (fhc, NULL);
534       return;
535     }
536   GNUNET_SCHEDULER_add_after (sched,
537                               run_on_shutdown,
538                               priority,
539                               GNUNET_SCHEDULER_NO_PREREQUISITE_TASK,
540                               &file_hash_task, fhc);
541 }
542
543
544 /* ***************** binary-ASCII encoding *************** */
545
546 /**
547  * 32 characters for encoding (GNUNET_CRYPTO_hash => 32 characters)
548  */
549 static char *encTable__ = "0123456789ABCDEFGHIJKLMNOPQRSTUV";
550
551 static unsigned int
552 getValue__ (unsigned char a)
553 {
554   if ((a >= '0') && (a <= '9'))
555     return a - '0';
556   if ((a >= 'A') && (a <= 'V'))
557     return (a - 'A' + 10);
558   return -1;
559 }
560
561 /**
562  * Convert GNUNET_CRYPTO_hash to ASCII encoding.  The ASCII encoding is rather
563  * GNUnet specific.  It was chosen such that it only uses characters
564  * in [0-9A-V], can be produced without complex arithmetics and uses a
565  * small number of characters.  The GNUnet encoding uses 102
566  * characters plus a null terminator.
567  *
568  * @param block the GNUNET_CRYPTO_hash code
569  * @param result where to store the encoding (struct GNUNET_CRYPTO_HashAsciiEncoded can be
570  *  safely cast to char*, a '\0' termination is set).
571  */
572 void
573 GNUNET_CRYPTO_hash_to_enc (const GNUNET_HashCode * block,
574                            struct GNUNET_CRYPTO_HashAsciiEncoded *result)
575 {
576   unsigned int wpos;
577   unsigned int rpos;
578   unsigned int bits;
579   unsigned int vbit;
580
581   GNUNET_assert (block != NULL);
582   GNUNET_assert (result != NULL);
583   vbit = 0;
584   wpos = 0;
585   rpos = 0;
586   bits = 0;
587   while ((rpos < sizeof (GNUNET_HashCode)) || (vbit > 0))
588     {
589       if ((rpos < sizeof (GNUNET_HashCode)) && (vbit < 5))
590         {
591           bits = (bits << 8) | ((unsigned char *) block)[rpos++];       /* eat 8 more bits */
592           vbit += 8;
593         }
594       if (vbit < 5)
595         {
596           bits <<= (5 - vbit);  /* zero-padding */
597           GNUNET_assert (vbit == 2);    /* padding by 3: 512+3 mod 5 == 0 */
598           vbit = 5;
599         }
600       GNUNET_assert (wpos <
601                      sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
602       result->encoding[wpos++] = encTable__[(bits >> (vbit - 5)) & 31];
603       vbit -= 5;
604     }
605   GNUNET_assert (wpos == sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1);
606   GNUNET_assert (vbit == 0);
607   result->encoding[wpos] = '\0';
608 }
609
610 /**
611  * Convert ASCII encoding back to GNUNET_CRYPTO_hash
612  *
613  * @param enc the encoding
614  * @param result where to store the GNUNET_CRYPTO_hash code
615  * @return GNUNET_OK on success, GNUNET_SYSERR if result has the wrong encoding
616  */
617 int
618 GNUNET_CRYPTO_hash_from_string (const char *enc, GNUNET_HashCode * result)
619 {
620   unsigned int rpos;
621   unsigned int wpos;
622   unsigned int bits;
623   unsigned int vbit;
624
625   if (strlen (enc) != sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1)
626     return GNUNET_SYSERR;
627
628   vbit = 2;                     /* padding! */
629   wpos = sizeof (GNUNET_HashCode);
630   rpos = sizeof (struct GNUNET_CRYPTO_HashAsciiEncoded) - 1;
631   bits = getValue__ (enc[--rpos]) >> 3;
632   while (wpos > 0)
633     {
634       GNUNET_assert (rpos > 0);
635       bits = (getValue__ (enc[--rpos]) << vbit) | bits;
636       vbit += 5;
637       if (vbit >= 8)
638         {
639           ((unsigned char *) result)[--wpos] = (unsigned char) bits;
640           bits >>= 8;
641           vbit -= 8;
642         }
643     }
644   GNUNET_assert (rpos == 0);
645   GNUNET_assert (vbit == 0);
646   return GNUNET_OK;
647 }
648
649 /**
650  * Compute the distance between 2 hashcodes.  The computation must be
651  * fast, not involve bits[0] or bits[4] (they're used elsewhere), and be
652  * somewhat consistent. And of course, the result should be a positive
653  * number.
654  *
655  * @returns a positive number which is a measure for
656  *  hashcode proximity.
657  */
658 unsigned int
659 GNUNET_CRYPTO_hash_distance_u32 (const GNUNET_HashCode * a,
660                                  const GNUNET_HashCode * b)
661 {
662   unsigned int x1 = (a->bits[1] - b->bits[1]) >> 16;
663   unsigned int x2 = (b->bits[1] - a->bits[1]) >> 16;
664   return (x1 * x2);
665 }
666
667 void
668 GNUNET_CRYPTO_hash_create_random (GNUNET_HashCode * result)
669 {
670   int i;
671   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
672        i--)
673     result->bits[i] = rand ();
674 }
675
676 void
677 GNUNET_CRYPTO_hash_difference (const GNUNET_HashCode * a,
678                                const GNUNET_HashCode * b,
679                                GNUNET_HashCode * result)
680 {
681   int i;
682   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
683        i--)
684     result->bits[i] = b->bits[i] - a->bits[i];
685 }
686
687 void
688 GNUNET_CRYPTO_hash_sum (const GNUNET_HashCode * a,
689                         const GNUNET_HashCode * delta,
690                         GNUNET_HashCode * result)
691 {
692   int i;
693   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
694        i--)
695     result->bits[i] = delta->bits[i] + a->bits[i];
696 }
697
698 void
699 GNUNET_CRYPTO_hash_xor (const GNUNET_HashCode * a,
700                         const GNUNET_HashCode * b, GNUNET_HashCode * result)
701 {
702   int i;
703   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
704        i--)
705     result->bits[i] = a->bits[i] ^ b->bits[i];
706 }
707
708 /**
709  * Convert a hashcode into a key.
710  */
711 void
712 GNUNET_CRYPTO_hash_to_AES_key (const GNUNET_HashCode * hc,
713                                struct GNUNET_CRYPTO_AesSessionKey *skey,
714                                struct GNUNET_CRYPTO_AesInitializationVector
715                                *iv)
716 {
717   GNUNET_assert (sizeof (GNUNET_HashCode) >=
718                  GNUNET_CRYPTO_AES_KEY_LENGTH +
719                  sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
720   memcpy (skey, hc, GNUNET_CRYPTO_AES_KEY_LENGTH);
721   skey->crc32 =
722     htonl (GNUNET_CRYPTO_crc32_n (skey, GNUNET_CRYPTO_AES_KEY_LENGTH));
723   memcpy (iv, &((char *) hc)[GNUNET_CRYPTO_AES_KEY_LENGTH],
724           sizeof (struct GNUNET_CRYPTO_AesInitializationVector));
725 }
726
727 /**
728  * Obtain a bit from a hashcode.
729  * @param code the GNUNET_CRYPTO_hash to index bit-wise
730  * @param bit index into the hashcode, [0...511]
731  * @return Bit \a bit from hashcode \a code, -1 for invalid index
732  */
733 int
734 GNUNET_CRYPTO_hash_get_bit (const GNUNET_HashCode * code, unsigned int bit)
735 {
736   GNUNET_assert (bit < 8 * sizeof (GNUNET_HashCode));
737   return (((unsigned char *) code)[bit >> 3] & (1 << (bit & 7))) > 0;
738 }
739
740 /**
741  * Compare function for HashCodes, producing a total ordering
742  * of all hashcodes.
743  * @return 1 if h1 > h2, -1 if h1 < h2 and 0 if h1 == h2.
744  */
745 int
746 GNUNET_CRYPTO_hash_cmp (const GNUNET_HashCode * h1,
747                         const GNUNET_HashCode * h2)
748 {
749   unsigned int *i1;
750   unsigned int *i2;
751   int i;
752
753   i1 = (unsigned int *) h1;
754   i2 = (unsigned int *) h2;
755   for (i = (sizeof (GNUNET_HashCode) / sizeof (unsigned int)) - 1; i >= 0;
756        i--)
757     {
758       if (i1[i] > i2[i])
759         return 1;
760       if (i1[i] < i2[i])
761         return -1;
762     }
763   return 0;
764 }
765
766 /**
767  * Find out which of the two GNUNET_CRYPTO_hash codes is closer to target
768  * in the XOR metric (Kademlia).
769  * @return -1 if h1 is closer, 1 if h2 is closer and 0 if h1==h2.
770  */
771 int
772 GNUNET_CRYPTO_hash_xorcmp (const GNUNET_HashCode * h1,
773                            const GNUNET_HashCode * h2,
774                            const GNUNET_HashCode * target)
775 {
776   int i;
777   unsigned int d1;
778   unsigned int d2;
779
780   for (i = sizeof (GNUNET_HashCode) / sizeof (unsigned int) - 1; i >= 0; i--)
781     {
782       d1 = ((unsigned int *) h1)[i] ^ ((unsigned int *) target)[i];
783       d2 = ((unsigned int *) h2)[i] ^ ((unsigned int *) target)[i];
784       if (d1 > d2)
785         return 1;
786       else if (d1 < d2)
787         return -1;
788     }
789   return 0;
790 }
791
792 /* end of hashing.c */