Make GChecksum more fully introspectable
[platform/upstream/glib.git] / glib / gchecksum.c
1 /* gchecksum.h - data hashing functions
2  *
3  * Copyright (C) 2007  Emmanuele Bassi  <ebassi@gnome.org>
4  *
5  * This library is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU Library General Public
7  * License as published by the Free Software Foundation; either
8  * version 2 of the License, or (at your option) any later version.
9  *
10  * This library is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13  * Library General Public License for more details.
14  *
15  * You should have received a copy of the GNU Library General Public
16  * License along with this library; if not, write to the
17  * Free Software Foundation, Inc., 59 Temple Place - Suite 330,
18  * Boston, MA 02111-1307, USA.
19  */
20
21 #include "config.h"
22
23 #include <string.h>
24
25 #include "gchecksum.h"
26
27 #include "gslice.h"
28 #include "gmem.h"
29 #include "gstrfuncs.h"
30 #include "gtestutils.h"
31 #include "gtypes.h"
32 #include "glibintl.h"
33
34
35 /**
36  * SECTION:checksum
37  * @title: Data Checksums
38  * @short_description: computes the checksum for data
39  *
40  * GLib provides a generic API for computing checksums (or "digests")
41  * for a sequence of arbitrary bytes, using various hashing algorithms
42  * like MD5, SHA-1 and SHA-256. Checksums are commonly used in various
43  * environments and specifications.
44  *
45  * GLib supports incremental checksums using the GChecksum data
46  * structure, by calling g_checksum_update() as long as there's data
47  * available and then using g_checksum_get_string() or
48  * g_checksum_get_digest() to compute the checksum and return it either
49  * as a string in hexadecimal form, or as a raw sequence of bytes. To
50  * compute the checksum for binary blobs and NUL-terminated strings in
51  * one go, use the convenience functions g_compute_checksum_for_data()
52  * and g_compute_checksum_for_string(), respectively.
53  *
54  * Support for checksums has been added in GLib 2.16
55  **/
56
57 #define IS_VALID_TYPE(type)     ((type) >= G_CHECKSUM_MD5 && (type) <= G_CHECKSUM_SHA512)
58
59 /* The fact that these are lower case characters is part of the ABI */
60 static const gchar hex_digits[] = "0123456789abcdef";
61
62 #define MD5_DATASIZE    64
63 #define MD5_DIGEST_LEN  16
64
65 typedef struct
66 {
67   guint32 buf[4];
68   guint32 bits[2];
69
70   union {
71     guchar data[MD5_DATASIZE];
72     guint32 data32[MD5_DATASIZE / 4];
73   } u;
74
75   guchar digest[MD5_DIGEST_LEN];
76 } Md5sum;
77
78 #define SHA1_DATASIZE   64
79 #define SHA1_DIGEST_LEN 20
80
81 typedef struct
82 {
83   guint32 buf[5];
84   guint32 bits[2];
85
86   /* we pack 64 unsigned chars into 16 32-bit unsigned integers */
87   guint32 data[16];
88
89   guchar digest[SHA1_DIGEST_LEN];
90 } Sha1sum;
91
92 #define SHA256_DATASIZE         64
93 #define SHA256_DIGEST_LEN       32
94
95 typedef struct
96 {
97   guint32 buf[8];
98   guint32 bits[2];
99
100   guint8 data[SHA256_DATASIZE];
101
102   guchar digest[SHA256_DIGEST_LEN];
103 } Sha256sum;
104
105 #define SHA512_BLOCK_LEN       128 /* 1024 bits message block */
106 #define SHA512_DIGEST_LEN       64
107
108 typedef struct
109 {
110   guint64 H[8];
111
112   guint8 block[SHA512_BLOCK_LEN];
113   guint8 block_len;
114
115   guint64 data_len[2];
116
117   guchar digest[SHA512_DIGEST_LEN];
118 } Sha512sum;
119
120 struct _GChecksum
121 {
122   GChecksumType type;
123
124   gchar *digest_str;
125
126   union {
127     Md5sum md5;
128     Sha1sum sha1;
129     Sha256sum sha256;
130     Sha512sum sha512;
131   } sum;
132 };
133
134 /* we need different byte swapping functions because MD5 expects buffers
135  * to be little-endian, while SHA1 and SHA256 expect them in big-endian
136  * form.
137  */
138
139 #if G_BYTE_ORDER == G_LITTLE_ENDIAN
140 #define md5_byte_reverse(buffer,length)
141 #else
142 /* assume that the passed buffer is integer aligned */
143 static inline void
144 md5_byte_reverse (guchar *buffer,
145                   gulong  length)
146 {
147   guint32 bit;
148
149   do
150     {
151       bit = (guint32) ((unsigned) buffer[3] << 8 | buffer[2]) << 16 |
152                       ((unsigned) buffer[1] << 8 | buffer[0]);
153       * (guint32 *) buffer = bit;
154       buffer += 4;
155     }
156   while (--length);
157 }
158 #endif /* G_BYTE_ORDER == G_LITTLE_ENDIAN */
159
160 #if G_BYTE_ORDER == G_BIG_ENDIAN
161 #define sha_byte_reverse(buffer,length)
162 #else
163 static inline void
164 sha_byte_reverse (guint32 *buffer,
165                   gint     length)
166 {
167   length /= sizeof (guint32);
168   while (length--)
169     {
170       *buffer = GUINT32_SWAP_LE_BE (*buffer);
171       ++buffer;
172     }
173 }
174 #endif /* G_BYTE_ORDER == G_BIG_ENDIAN */
175
176 static gchar *
177 digest_to_string (guint8 *digest,
178                   gsize   digest_len)
179 {
180   gint len = digest_len * 2;
181   gint i;
182   gchar *retval;
183
184   retval = g_new (gchar, len + 1);
185
186   for (i = 0; i < digest_len; i++)
187     {
188       guint8 byte = digest[i];
189
190       retval[2 * i] = hex_digits[byte >> 4];
191       retval[2 * i + 1] = hex_digits[byte & 0xf];
192     }
193
194   retval[len] = 0;
195
196   return retval;
197 }
198
199 /*
200  * MD5 Checksum
201  */
202
203 /* This MD5 digest computation is based on the equivalent code
204  * written by Colin Plumb. It came with this notice:
205  *
206  * This code implements the MD5 message-digest algorithm.
207  * The algorithm is due to Ron Rivest.  This code was
208  * written by Colin Plumb in 1993, no copyright is claimed.
209  * This code is in the public domain; do with it what you wish.
210  *
211  * Equivalent code is available from RSA Data Security, Inc.
212  * This code has been tested against that, and is equivalent,
213  * except that you don't need to include two pages of legalese
214  * with every copy.
215  */
216
217 static void
218 md5_sum_init (Md5sum *md5)
219 {
220   /* arbitrary constants */
221   md5->buf[0] = 0x67452301;
222   md5->buf[1] = 0xefcdab89;
223   md5->buf[2] = 0x98badcfe;
224   md5->buf[3] = 0x10325476;
225
226   md5->bits[0] = md5->bits[1] = 0;
227 }
228
229 /*
230  * The core of the MD5 algorithm, this alters an existing MD5 hash to
231  * reflect the addition of 16 longwords of new data.  md5_sum_update()
232  * blocks the data and converts bytes into longwords for this routine.
233  */
234 static void
235 md5_transform (guint32       buf[4],
236                guint32 const in[16])
237 {
238   register guint32 a, b, c, d;
239
240 /* The four core functions - F1 is optimized somewhat */
241 #define F1(x, y, z)     (z ^ (x & (y ^ z)))
242 #define F2(x, y, z)     F1 (z, x, y)
243 #define F3(x, y, z)     (x ^ y ^ z)
244 #define F4(x, y, z)     (y ^ (x | ~z))
245
246 /* This is the central step in the MD5 algorithm. */
247 #define md5_step(f, w, x, y, z, data, s) \
248         ( w += f (x, y, z) + data,  w = w << s | w >> (32 - s),  w += x )
249
250   a = buf[0];
251   b = buf[1];
252   c = buf[2];
253   d = buf[3];
254
255   md5_step (F1, a, b, c, d, in[0]  + 0xd76aa478,  7);
256   md5_step (F1, d, a, b, c, in[1]  + 0xe8c7b756, 12);
257   md5_step (F1, c, d, a, b, in[2]  + 0x242070db, 17);
258   md5_step (F1, b, c, d, a, in[3]  + 0xc1bdceee, 22);
259   md5_step (F1, a, b, c, d, in[4]  + 0xf57c0faf,  7);
260   md5_step (F1, d, a, b, c, in[5]  + 0x4787c62a, 12);
261   md5_step (F1, c, d, a, b, in[6]  + 0xa8304613, 17);
262   md5_step (F1, b, c, d, a, in[7]  + 0xfd469501, 22);
263   md5_step (F1, a, b, c, d, in[8]  + 0x698098d8,  7);
264   md5_step (F1, d, a, b, c, in[9]  + 0x8b44f7af, 12);
265   md5_step (F1, c, d, a, b, in[10] + 0xffff5bb1, 17);
266   md5_step (F1, b, c, d, a, in[11] + 0x895cd7be, 22);
267   md5_step (F1, a, b, c, d, in[12] + 0x6b901122,  7);
268   md5_step (F1, d, a, b, c, in[13] + 0xfd987193, 12);
269   md5_step (F1, c, d, a, b, in[14] + 0xa679438e, 17);
270   md5_step (F1, b, c, d, a, in[15] + 0x49b40821, 22);
271         
272   md5_step (F2, a, b, c, d, in[1]  + 0xf61e2562,  5);
273   md5_step (F2, d, a, b, c, in[6]  + 0xc040b340,  9);
274   md5_step (F2, c, d, a, b, in[11] + 0x265e5a51, 14);
275   md5_step (F2, b, c, d, a, in[0]  + 0xe9b6c7aa, 20);
276   md5_step (F2, a, b, c, d, in[5]  + 0xd62f105d,  5);
277   md5_step (F2, d, a, b, c, in[10] + 0x02441453,  9);
278   md5_step (F2, c, d, a, b, in[15] + 0xd8a1e681, 14);
279   md5_step (F2, b, c, d, a, in[4]  + 0xe7d3fbc8, 20);
280   md5_step (F2, a, b, c, d, in[9]  + 0x21e1cde6,  5);
281   md5_step (F2, d, a, b, c, in[14] + 0xc33707d6,  9);
282   md5_step (F2, c, d, a, b, in[3]  + 0xf4d50d87, 14);
283   md5_step (F2, b, c, d, a, in[8]  + 0x455a14ed, 20);
284   md5_step (F2, a, b, c, d, in[13] + 0xa9e3e905,  5);
285   md5_step (F2, d, a, b, c, in[2]  + 0xfcefa3f8,  9);
286   md5_step (F2, c, d, a, b, in[7]  + 0x676f02d9, 14);
287   md5_step (F2, b, c, d, a, in[12] + 0x8d2a4c8a, 20);
288
289   md5_step (F3, a, b, c, d, in[5]  + 0xfffa3942,  4);
290   md5_step (F3, d, a, b, c, in[8]  + 0x8771f681, 11);
291   md5_step (F3, c, d, a, b, in[11] + 0x6d9d6122, 16);
292   md5_step (F3, b, c, d, a, in[14] + 0xfde5380c, 23);
293   md5_step (F3, a, b, c, d, in[1]  + 0xa4beea44,  4);
294   md5_step (F3, d, a, b, c, in[4]  + 0x4bdecfa9, 11);
295   md5_step (F3, c, d, a, b, in[7]  + 0xf6bb4b60, 16);
296   md5_step (F3, b, c, d, a, in[10] + 0xbebfbc70, 23);
297   md5_step (F3, a, b, c, d, in[13] + 0x289b7ec6,  4);
298   md5_step (F3, d, a, b, c, in[0]  + 0xeaa127fa, 11);
299   md5_step (F3, c, d, a, b, in[3]  + 0xd4ef3085, 16);
300   md5_step (F3, b, c, d, a, in[6]  + 0x04881d05, 23);
301   md5_step (F3, a, b, c, d, in[9]  + 0xd9d4d039,  4);
302   md5_step (F3, d, a, b, c, in[12] + 0xe6db99e5, 11);
303   md5_step (F3, c, d, a, b, in[15] + 0x1fa27cf8, 16);
304   md5_step (F3, b, c, d, a, in[2]  + 0xc4ac5665, 23);
305
306   md5_step (F4, a, b, c, d, in[0]  + 0xf4292244,  6);
307   md5_step (F4, d, a, b, c, in[7]  + 0x432aff97, 10);
308   md5_step (F4, c, d, a, b, in[14] + 0xab9423a7, 15);
309   md5_step (F4, b, c, d, a, in[5]  + 0xfc93a039, 21);
310   md5_step (F4, a, b, c, d, in[12] + 0x655b59c3,  6);
311   md5_step (F4, d, a, b, c, in[3]  + 0x8f0ccc92, 10);
312   md5_step (F4, c, d, a, b, in[10] + 0xffeff47d, 15);
313   md5_step (F4, b, c, d, a, in[1]  + 0x85845dd1, 21);
314   md5_step (F4, a, b, c, d, in[8]  + 0x6fa87e4f,  6);
315   md5_step (F4, d, a, b, c, in[15] + 0xfe2ce6e0, 10);
316   md5_step (F4, c, d, a, b, in[6]  + 0xa3014314, 15);
317   md5_step (F4, b, c, d, a, in[13] + 0x4e0811a1, 21);
318   md5_step (F4, a, b, c, d, in[4]  + 0xf7537e82,  6);
319   md5_step (F4, d, a, b, c, in[11] + 0xbd3af235, 10);
320   md5_step (F4, c, d, a, b, in[2]  + 0x2ad7d2bb, 15);
321   md5_step (F4, b, c, d, a, in[9]  + 0xeb86d391, 21);
322
323   buf[0] += a;
324   buf[1] += b;
325   buf[2] += c;
326   buf[3] += d;
327
328 #undef F1
329 #undef F2
330 #undef F3
331 #undef F4
332 #undef md5_step
333 }
334
335 static void
336 md5_sum_update (Md5sum       *md5,
337                 const guchar *data,
338                 gsize         length)
339 {
340   guint32 bit;
341
342   bit = md5->bits[0];
343   md5->bits[0] = bit + ((guint32) length << 3);
344
345   /* carry from low to high */
346   if (md5->bits[0] < bit)
347     md5->bits[1] += 1;
348
349   md5->bits[1] += length >> 29;
350
351   /* bytes already in Md5sum->u.data */
352   bit = (bit >> 3) & 0x3f;
353
354   /* handle any leading odd-sized chunks */
355   if (bit)
356     {
357       guchar *p = md5->u.data + bit;
358
359       bit = MD5_DATASIZE - bit;
360       if (length < bit)
361         {
362           memcpy (p, data, length);
363           return;
364         }
365
366       memcpy (p, data, bit);
367
368       md5_byte_reverse (md5->u.data, 16);
369       md5_transform (md5->buf, md5->u.data32);
370
371       data += bit;
372       length -= bit;
373     }
374
375   /* process data in 64-byte chunks */
376   while (length >= MD5_DATASIZE)
377     {
378       memcpy (md5->u.data, data, MD5_DATASIZE);
379
380       md5_byte_reverse (md5->u.data, 16);
381       md5_transform (md5->buf, md5->u.data32);
382
383       data += MD5_DATASIZE;
384       length -= MD5_DATASIZE;
385     }
386
387   /* handle any remaining bytes of data */
388   memcpy (md5->u.data, data, length);
389 }
390
391 /* closes a checksum */
392 static void
393 md5_sum_close (Md5sum *md5)
394 {
395   guint count;
396   guchar *p;
397
398   /* Compute number of bytes mod 64 */
399   count = (md5->bits[0] >> 3) & 0x3F;
400
401   /* Set the first char of padding to 0x80.
402    * This is safe since there is always at least one byte free
403    */
404   p = md5->u.data + count;
405   *p++ = 0x80;
406
407   /* Bytes of padding needed to make 64 bytes */
408   count = MD5_DATASIZE - 1 - count;
409
410   /* Pad out to 56 mod 64 */
411   if (count < 8)
412     {
413       /* Two lots of padding:  Pad the first block to 64 bytes */
414       memset (p, 0, count);
415
416       md5_byte_reverse (md5->u.data, 16);
417       md5_transform (md5->buf, md5->u.data32);
418
419       /* Now fill the next block with 56 bytes */
420       memset (md5->u.data, 0, MD5_DATASIZE - 8);
421     }
422   else
423     {
424       /* Pad block to 56 bytes */
425       memset (p, 0, count - 8);
426     }
427
428   md5_byte_reverse (md5->u.data, 14);
429
430   /* Append length in bits and transform */
431   md5->u.data32[14] = md5->bits[0];
432   md5->u.data32[15] = md5->bits[1];
433
434   md5_transform (md5->buf, md5->u.data32);
435   md5_byte_reverse ((guchar *) md5->buf, 4);
436
437   memcpy (md5->digest, md5->buf, 16);
438
439   /* Reset buffers in case they contain sensitive data */
440   memset (md5->buf, 0, sizeof (md5->buf));
441   memset (md5->u.data, 0, sizeof (md5->u.data));
442 }
443
444 static gchar *
445 md5_sum_to_string (Md5sum *md5)
446 {
447   return digest_to_string (md5->digest, MD5_DIGEST_LEN);
448 }
449
450 static void
451 md5_sum_digest (Md5sum *md5,
452                 guint8 *digest)
453 {
454   gint i;
455
456   for (i = 0; i < MD5_DIGEST_LEN; i++)
457     digest[i] = md5->digest[i];
458 }
459
460 /*
461  * SHA-1 Checksum
462  */
463
464 /* The following implementation comes from D-Bus dbus-sha.c. I've changed
465  * it to use GLib types and to work more like the MD5 implementation above.
466  * I left the comments to have an history of this code.
467  *      -- Emmanuele Bassi, ebassi@gnome.org
468  */
469
470 /* The following comments have the history of where this code
471  * comes from. I actually copied it from GNet in GNOME CVS.
472  * - hp@redhat.com
473  */
474
475 /*
476  *  sha.h : Implementation of the Secure Hash Algorithm
477  *
478  * Part of the Python Cryptography Toolkit, version 1.0.0
479  *
480  * Copyright (C) 1995, A.M. Kuchling
481  *
482  * Distribute and use freely; there are no restrictions on further
483  * dissemination and usage except those imposed by the laws of your
484  * country of residence.
485  *
486  */
487
488 /* SHA: NIST's Secure Hash Algorithm */
489
490 /* Based on SHA code originally posted to sci.crypt by Peter Gutmann
491    in message <30ajo5$oe8@ccu2.auckland.ac.nz>.
492    Modified to test for endianness on creation of SHA objects by AMK.
493    Also, the original specification of SHA was found to have a weakness
494    by NSA/NIST.  This code implements the fixed version of SHA.
495 */
496
497 /* Here's the first paragraph of Peter Gutmann's posting:
498
499 The following is my SHA (FIPS 180) code updated to allow use of the "fixed"
500 SHA, thanks to Jim Gillogly and an anonymous contributor for the information on
501 what's changed in the new version.  The fix is a simple change which involves
502 adding a single rotate in the initial expansion function.  It is unknown
503 whether this is an optimal solution to the problem which was discovered in the
504 SHA or whether it's simply a bandaid which fixes the problem with a minimum of
505 effort (for example the reengineering of a great many Capstone chips).
506 */
507
508 static void
509 sha1_sum_init (Sha1sum *sha1)
510 {
511   /* initialize constants */
512   sha1->buf[0] = 0x67452301L;
513   sha1->buf[1] = 0xEFCDAB89L;
514   sha1->buf[2] = 0x98BADCFEL;
515   sha1->buf[3] = 0x10325476L;
516   sha1->buf[4] = 0xC3D2E1F0L;
517
518   /* initialize bits */
519   sha1->bits[0] = sha1->bits[1] = 0;
520 }
521
522 /* The SHA f()-functions. */
523
524 #define f1(x,y,z)       (z ^ (x & (y ^ z)))             /* Rounds  0-19 */
525 #define f2(x,y,z)       (x ^ y ^ z)                     /* Rounds 20-39 */
526 #define f3(x,y,z)       (( x & y) | (z & (x | y)))      /* Rounds 40-59 */
527 #define f4(x,y,z)       (x ^ y ^ z)                     /* Rounds 60-79 */
528
529 /* The SHA Mysterious Constants */
530 #define K1  0x5A827999L                                 /* Rounds  0-19 */
531 #define K2  0x6ED9EBA1L                                 /* Rounds 20-39 */
532 #define K3  0x8F1BBCDCL                                 /* Rounds 40-59 */
533 #define K4  0xCA62C1D6L                                 /* Rounds 60-79 */
534
535 /* 32-bit rotate left - kludged with shifts */
536 #define ROTL(n,X) (((X) << n ) | ((X) >> (32 - n)))
537
538 /* The initial expanding function.  The hash function is defined over an
539    80-word expanded input array W, where the first 16 are copies of the input
540    data, and the remaining 64 are defined by
541
542         W[ i ] = W[ i - 16 ] ^ W[ i - 14 ] ^ W[ i - 8 ] ^ W[ i - 3 ]
543
544    This implementation generates these values on the fly in a circular
545    buffer - thanks to Colin Plumb, colin@nyx10.cs.du.edu for this
546    optimization.
547
548    The updated SHA changes the expanding function by adding a rotate of 1
549    bit.  Thanks to Jim Gillogly, jim@rand.org, and an anonymous contributor
550    for this information */
551
552 #define expand(W,i) (W[ i & 15 ] = ROTL (1, (W[ i       & 15] ^ \
553                                              W[(i - 14) & 15] ^ \
554                                              W[(i -  8) & 15] ^ \
555                                              W[(i -  3) & 15])))
556
557
558 /* The prototype SHA sub-round.  The fundamental sub-round is:
559
560         a' = e + ROTL( 5, a ) + f( b, c, d ) + k + data;
561         b' = a;
562         c' = ROTL( 30, b );
563         d' = c;
564         e' = d;
565
566    but this is implemented by unrolling the loop 5 times and renaming the
567    variables ( e, a, b, c, d ) = ( a', b', c', d', e' ) each iteration.
568    This code is then replicated 20 times for each of the 4 functions, using
569    the next 20 values from the W[] array each time */
570
571 #define subRound(a, b, c, d, e, f, k, data) \
572    (e += ROTL (5, a) + f(b, c, d) + k + data, b = ROTL (30, b))
573
574 static void
575 sha1_transform (guint32  buf[5],
576                 guint32  in[16])
577 {
578   guint32 A, B, C, D, E;
579
580   A = buf[0];
581   B = buf[1];
582   C = buf[2];
583   D = buf[3];
584   E = buf[4];
585
586   /* Heavy mangling, in 4 sub-rounds of 20 iterations each. */
587   subRound (A, B, C, D, E, f1, K1, in[0]);
588   subRound (E, A, B, C, D, f1, K1, in[1]);
589   subRound (D, E, A, B, C, f1, K1, in[2]);
590   subRound (C, D, E, A, B, f1, K1, in[3]);
591   subRound (B, C, D, E, A, f1, K1, in[4]);
592   subRound (A, B, C, D, E, f1, K1, in[5]);
593   subRound (E, A, B, C, D, f1, K1, in[6]);
594   subRound (D, E, A, B, C, f1, K1, in[7]);
595   subRound (C, D, E, A, B, f1, K1, in[8]);
596   subRound (B, C, D, E, A, f1, K1, in[9]);
597   subRound (A, B, C, D, E, f1, K1, in[10]);
598   subRound (E, A, B, C, D, f1, K1, in[11]);
599   subRound (D, E, A, B, C, f1, K1, in[12]);
600   subRound (C, D, E, A, B, f1, K1, in[13]);
601   subRound (B, C, D, E, A, f1, K1, in[14]);
602   subRound (A, B, C, D, E, f1, K1, in[15]);
603   subRound (E, A, B, C, D, f1, K1, expand (in, 16));
604   subRound (D, E, A, B, C, f1, K1, expand (in, 17));
605   subRound (C, D, E, A, B, f1, K1, expand (in, 18));
606   subRound (B, C, D, E, A, f1, K1, expand (in, 19));
607
608   subRound (A, B, C, D, E, f2, K2, expand (in, 20));
609   subRound (E, A, B, C, D, f2, K2, expand (in, 21));
610   subRound (D, E, A, B, C, f2, K2, expand (in, 22));
611   subRound (C, D, E, A, B, f2, K2, expand (in, 23));
612   subRound (B, C, D, E, A, f2, K2, expand (in, 24));
613   subRound (A, B, C, D, E, f2, K2, expand (in, 25));
614   subRound (E, A, B, C, D, f2, K2, expand (in, 26));
615   subRound (D, E, A, B, C, f2, K2, expand (in, 27));
616   subRound (C, D, E, A, B, f2, K2, expand (in, 28));
617   subRound (B, C, D, E, A, f2, K2, expand (in, 29));
618   subRound (A, B, C, D, E, f2, K2, expand (in, 30));
619   subRound (E, A, B, C, D, f2, K2, expand (in, 31));
620   subRound (D, E, A, B, C, f2, K2, expand (in, 32));
621   subRound (C, D, E, A, B, f2, K2, expand (in, 33));
622   subRound (B, C, D, E, A, f2, K2, expand (in, 34));
623   subRound (A, B, C, D, E, f2, K2, expand (in, 35));
624   subRound (E, A, B, C, D, f2, K2, expand (in, 36));
625   subRound (D, E, A, B, C, f2, K2, expand (in, 37));
626   subRound (C, D, E, A, B, f2, K2, expand (in, 38));
627   subRound (B, C, D, E, A, f2, K2, expand (in, 39));
628
629   subRound (A, B, C, D, E, f3, K3, expand (in, 40));
630   subRound (E, A, B, C, D, f3, K3, expand (in, 41));
631   subRound (D, E, A, B, C, f3, K3, expand (in, 42));
632   subRound (C, D, E, A, B, f3, K3, expand (in, 43));
633   subRound (B, C, D, E, A, f3, K3, expand (in, 44));
634   subRound (A, B, C, D, E, f3, K3, expand (in, 45));
635   subRound (E, A, B, C, D, f3, K3, expand (in, 46));
636   subRound (D, E, A, B, C, f3, K3, expand (in, 47));
637   subRound (C, D, E, A, B, f3, K3, expand (in, 48));
638   subRound (B, C, D, E, A, f3, K3, expand (in, 49));
639   subRound (A, B, C, D, E, f3, K3, expand (in, 50));
640   subRound (E, A, B, C, D, f3, K3, expand (in, 51));
641   subRound (D, E, A, B, C, f3, K3, expand (in, 52));
642   subRound (C, D, E, A, B, f3, K3, expand (in, 53));
643   subRound (B, C, D, E, A, f3, K3, expand (in, 54));
644   subRound (A, B, C, D, E, f3, K3, expand (in, 55));
645   subRound (E, A, B, C, D, f3, K3, expand (in, 56));
646   subRound (D, E, A, B, C, f3, K3, expand (in, 57));
647   subRound (C, D, E, A, B, f3, K3, expand (in, 58));
648   subRound (B, C, D, E, A, f3, K3, expand (in, 59));
649
650   subRound (A, B, C, D, E, f4, K4, expand (in, 60));
651   subRound (E, A, B, C, D, f4, K4, expand (in, 61));
652   subRound (D, E, A, B, C, f4, K4, expand (in, 62));
653   subRound (C, D, E, A, B, f4, K4, expand (in, 63));
654   subRound (B, C, D, E, A, f4, K4, expand (in, 64));
655   subRound (A, B, C, D, E, f4, K4, expand (in, 65));
656   subRound (E, A, B, C, D, f4, K4, expand (in, 66));
657   subRound (D, E, A, B, C, f4, K4, expand (in, 67));
658   subRound (C, D, E, A, B, f4, K4, expand (in, 68));
659   subRound (B, C, D, E, A, f4, K4, expand (in, 69));
660   subRound (A, B, C, D, E, f4, K4, expand (in, 70));
661   subRound (E, A, B, C, D, f4, K4, expand (in, 71));
662   subRound (D, E, A, B, C, f4, K4, expand (in, 72));
663   subRound (C, D, E, A, B, f4, K4, expand (in, 73));
664   subRound (B, C, D, E, A, f4, K4, expand (in, 74));
665   subRound (A, B, C, D, E, f4, K4, expand (in, 75));
666   subRound (E, A, B, C, D, f4, K4, expand (in, 76));
667   subRound (D, E, A, B, C, f4, K4, expand (in, 77));
668   subRound (C, D, E, A, B, f4, K4, expand (in, 78));
669   subRound (B, C, D, E, A, f4, K4, expand (in, 79));
670
671   /* Build message digest */
672   buf[0] += A;
673   buf[1] += B;
674   buf[2] += C;
675   buf[3] += D;
676   buf[4] += E;
677 }
678
679 #undef K1
680 #undef K2
681 #undef K3
682 #undef K4
683 #undef f1
684 #undef f2
685 #undef f3
686 #undef f4
687 #undef ROTL
688 #undef expand
689 #undef subRound
690
691 static void
692 sha1_sum_update (Sha1sum      *sha1,
693                  const guchar *buffer,
694                  gsize         count)
695 {
696   guint32 tmp;
697   guint dataCount;
698
699   /* Update bitcount */
700   tmp = sha1->bits[0];
701   if ((sha1->bits[0] = tmp + ((guint32) count << 3) ) < tmp)
702     sha1->bits[1] += 1;             /* Carry from low to high */
703   sha1->bits[1] += count >> 29;
704
705   /* Get count of bytes already in data */
706   dataCount = (guint) (tmp >> 3) & 0x3F;
707
708   /* Handle any leading odd-sized chunks */
709   if (dataCount)
710     {
711       guchar *p = (guchar *) sha1->data + dataCount;
712
713       dataCount = SHA1_DATASIZE - dataCount;
714       if (count < dataCount)
715         {
716           memcpy (p, buffer, count);
717           return;
718         }
719
720       memcpy (p, buffer, dataCount);
721
722       sha_byte_reverse (sha1->data, SHA1_DATASIZE);
723       sha1_transform (sha1->buf, sha1->data);
724
725       buffer += dataCount;
726       count -= dataCount;
727     }
728
729   /* Process data in SHA1_DATASIZE chunks */
730   while (count >= SHA1_DATASIZE)
731     {
732       memcpy (sha1->data, buffer, SHA1_DATASIZE);
733
734       sha_byte_reverse (sha1->data, SHA1_DATASIZE);
735       sha1_transform (sha1->buf, sha1->data);
736
737       buffer += SHA1_DATASIZE;
738       count -= SHA1_DATASIZE;
739     }
740
741   /* Handle any remaining bytes of data. */
742   memcpy (sha1->data, buffer, count);
743 }
744
745 /* Final wrapup - pad to SHA_DATASIZE-byte boundary with the bit pattern
746    1 0* (64-bit count of bits processed, MSB-first) */
747 static void
748 sha1_sum_close (Sha1sum *sha1)
749 {
750   gint count;
751   guchar *data_p;
752
753   /* Compute number of bytes mod 64 */
754   count = (gint) ((sha1->bits[0] >> 3) & 0x3f);
755
756   /* Set the first char of padding to 0x80.  This is safe since there is
757      always at least one byte free */
758   data_p = (guchar *) sha1->data + count;
759   *data_p++ = 0x80;
760
761   /* Bytes of padding needed to make 64 bytes */
762   count = SHA1_DATASIZE - 1 - count;
763
764   /* Pad out to 56 mod 64 */
765   if (count < 8)
766     {
767       /* Two lots of padding:  Pad the first block to 64 bytes */
768       memset (data_p, 0, count);
769
770       sha_byte_reverse (sha1->data, SHA1_DATASIZE);
771       sha1_transform (sha1->buf, sha1->data);
772
773       /* Now fill the next block with 56 bytes */
774       memset (sha1->data, 0, SHA1_DATASIZE - 8);
775     }
776   else
777     {
778       /* Pad block to 56 bytes */
779       memset (data_p, 0, count - 8);
780     }
781
782   /* Append length in bits and transform */
783   sha1->data[14] = sha1->bits[1];
784   sha1->data[15] = sha1->bits[0];
785
786   sha_byte_reverse (sha1->data, SHA1_DATASIZE - 8);
787   sha1_transform (sha1->buf, sha1->data);
788   sha_byte_reverse (sha1->buf, SHA1_DIGEST_LEN);
789
790   memcpy (sha1->digest, sha1->buf, SHA1_DIGEST_LEN);
791
792   /* Reset buffers in case they contain sensitive data */
793   memset (sha1->buf, 0, sizeof (sha1->buf));
794   memset (sha1->data, 0, sizeof (sha1->data));
795 }
796
797 static gchar *
798 sha1_sum_to_string (Sha1sum *sha1)
799 {
800   return digest_to_string (sha1->digest, SHA1_DIGEST_LEN);
801 }
802
803 static void
804 sha1_sum_digest (Sha1sum *sha1,
805                  guint8  *digest)
806 {
807   gint i;
808
809   for (i = 0; i < SHA1_DIGEST_LEN; i++)
810     digest[i] = sha1->digest[i];
811 }
812
813 /*
814  * SHA-256 Checksum
815  */
816
817 /* adapted from the SHA256 implementation in gsk/src/hash/gskhash.c.
818  *
819  * Copyright (C) 2006 Dave Benson
820  * Released under the terms of the GNU Lesser General Public License
821  */
822
823 static void
824 sha256_sum_init (Sha256sum *sha256)
825 {
826   sha256->buf[0] = 0x6a09e667;
827   sha256->buf[1] = 0xbb67ae85;
828   sha256->buf[2] = 0x3c6ef372;
829   sha256->buf[3] = 0xa54ff53a;
830   sha256->buf[4] = 0x510e527f;
831   sha256->buf[5] = 0x9b05688c;
832   sha256->buf[6] = 0x1f83d9ab;
833   sha256->buf[7] = 0x5be0cd19;
834
835   sha256->bits[0] = sha256->bits[1] = 0;
836 }
837
838 #define GET_UINT32(n,b,i)               G_STMT_START{   \
839     (n) = ((guint32) (b)[(i)    ] << 24)                \
840         | ((guint32) (b)[(i) + 1] << 16)                \
841         | ((guint32) (b)[(i) + 2] <<  8)                \
842         | ((guint32) (b)[(i) + 3]      ); } G_STMT_END
843
844 #define PUT_UINT32(n,b,i)               G_STMT_START{   \
845     (b)[(i)    ] = (guint8) ((n) >> 24);                \
846     (b)[(i) + 1] = (guint8) ((n) >> 16);                \
847     (b)[(i) + 2] = (guint8) ((n) >>  8);                \
848     (b)[(i) + 3] = (guint8) ((n)      ); } G_STMT_END
849
850 static void
851 sha256_transform (guint32      buf[8],
852                   guint8 const data[64])
853 {
854   guint32 temp1, temp2, W[64];
855   guint32 A, B, C, D, E, F, G, H;
856
857   GET_UINT32 (W[0],  data,  0);
858   GET_UINT32 (W[1],  data,  4);
859   GET_UINT32 (W[2],  data,  8);
860   GET_UINT32 (W[3],  data, 12);
861   GET_UINT32 (W[4],  data, 16);
862   GET_UINT32 (W[5],  data, 20);
863   GET_UINT32 (W[6],  data, 24);
864   GET_UINT32 (W[7],  data, 28);
865   GET_UINT32 (W[8],  data, 32);
866   GET_UINT32 (W[9],  data, 36);
867   GET_UINT32 (W[10], data, 40);
868   GET_UINT32 (W[11], data, 44);
869   GET_UINT32 (W[12], data, 48);
870   GET_UINT32 (W[13], data, 52);
871   GET_UINT32 (W[14], data, 56);
872   GET_UINT32 (W[15], data, 60);
873
874 #define SHR(x,n)        ((x & 0xFFFFFFFF) >> n)
875 #define ROTR(x,n)       (SHR (x,n) | (x << (32 - n)))
876
877 #define S0(x) (ROTR (x, 7) ^ ROTR (x,18) ^  SHR (x, 3))
878 #define S1(x) (ROTR (x,17) ^ ROTR (x,19) ^  SHR (x,10))
879 #define S2(x) (ROTR (x, 2) ^ ROTR (x,13) ^ ROTR (x,22))
880 #define S3(x) (ROTR (x, 6) ^ ROTR (x,11) ^ ROTR (x,25))
881
882 #define F0(x,y,z) ((x & y) | (z & (x | y)))
883 #define F1(x,y,z) (z ^ (x & (y ^ z)))
884
885 #define R(t)    (W[t] = S1(W[t -  2]) + W[t -  7] + \
886                         S0(W[t - 15]) + W[t - 16])
887
888 #define P(a,b,c,d,e,f,g,h,x,K)          G_STMT_START {  \
889         temp1 = h + S3(e) + F1(e,f,g) + K + x;          \
890         temp2 = S2(a) + F0(a,b,c);                      \
891         d += temp1; h = temp1 + temp2; } G_STMT_END
892
893   A = buf[0];
894   B = buf[1];
895   C = buf[2];
896   D = buf[3];
897   E = buf[4];
898   F = buf[5];
899   G = buf[6];
900   H = buf[7];
901
902   P (A, B, C, D, E, F, G, H, W[ 0], 0x428A2F98);
903   P (H, A, B, C, D, E, F, G, W[ 1], 0x71374491);
904   P (G, H, A, B, C, D, E, F, W[ 2], 0xB5C0FBCF);
905   P (F, G, H, A, B, C, D, E, W[ 3], 0xE9B5DBA5);
906   P (E, F, G, H, A, B, C, D, W[ 4], 0x3956C25B);
907   P (D, E, F, G, H, A, B, C, W[ 5], 0x59F111F1);
908   P (C, D, E, F, G, H, A, B, W[ 6], 0x923F82A4);
909   P (B, C, D, E, F, G, H, A, W[ 7], 0xAB1C5ED5);
910   P (A, B, C, D, E, F, G, H, W[ 8], 0xD807AA98);
911   P (H, A, B, C, D, E, F, G, W[ 9], 0x12835B01);
912   P (G, H, A, B, C, D, E, F, W[10], 0x243185BE);
913   P (F, G, H, A, B, C, D, E, W[11], 0x550C7DC3);
914   P (E, F, G, H, A, B, C, D, W[12], 0x72BE5D74);
915   P (D, E, F, G, H, A, B, C, W[13], 0x80DEB1FE);
916   P (C, D, E, F, G, H, A, B, W[14], 0x9BDC06A7);
917   P (B, C, D, E, F, G, H, A, W[15], 0xC19BF174);
918   P (A, B, C, D, E, F, G, H, R(16), 0xE49B69C1);
919   P (H, A, B, C, D, E, F, G, R(17), 0xEFBE4786);
920   P (G, H, A, B, C, D, E, F, R(18), 0x0FC19DC6);
921   P (F, G, H, A, B, C, D, E, R(19), 0x240CA1CC);
922   P (E, F, G, H, A, B, C, D, R(20), 0x2DE92C6F);
923   P (D, E, F, G, H, A, B, C, R(21), 0x4A7484AA);
924   P (C, D, E, F, G, H, A, B, R(22), 0x5CB0A9DC);
925   P (B, C, D, E, F, G, H, A, R(23), 0x76F988DA);
926   P (A, B, C, D, E, F, G, H, R(24), 0x983E5152);
927   P (H, A, B, C, D, E, F, G, R(25), 0xA831C66D);
928   P (G, H, A, B, C, D, E, F, R(26), 0xB00327C8);
929   P (F, G, H, A, B, C, D, E, R(27), 0xBF597FC7);
930   P (E, F, G, H, A, B, C, D, R(28), 0xC6E00BF3);
931   P (D, E, F, G, H, A, B, C, R(29), 0xD5A79147);
932   P (C, D, E, F, G, H, A, B, R(30), 0x06CA6351);
933   P (B, C, D, E, F, G, H, A, R(31), 0x14292967);
934   P (A, B, C, D, E, F, G, H, R(32), 0x27B70A85);
935   P (H, A, B, C, D, E, F, G, R(33), 0x2E1B2138);
936   P (G, H, A, B, C, D, E, F, R(34), 0x4D2C6DFC);
937   P (F, G, H, A, B, C, D, E, R(35), 0x53380D13);
938   P (E, F, G, H, A, B, C, D, R(36), 0x650A7354);
939   P (D, E, F, G, H, A, B, C, R(37), 0x766A0ABB);
940   P (C, D, E, F, G, H, A, B, R(38), 0x81C2C92E);
941   P (B, C, D, E, F, G, H, A, R(39), 0x92722C85);
942   P (A, B, C, D, E, F, G, H, R(40), 0xA2BFE8A1);
943   P (H, A, B, C, D, E, F, G, R(41), 0xA81A664B);
944   P (G, H, A, B, C, D, E, F, R(42), 0xC24B8B70);
945   P (F, G, H, A, B, C, D, E, R(43), 0xC76C51A3);
946   P (E, F, G, H, A, B, C, D, R(44), 0xD192E819);
947   P (D, E, F, G, H, A, B, C, R(45), 0xD6990624);
948   P (C, D, E, F, G, H, A, B, R(46), 0xF40E3585);
949   P (B, C, D, E, F, G, H, A, R(47), 0x106AA070);
950   P (A, B, C, D, E, F, G, H, R(48), 0x19A4C116);
951   P (H, A, B, C, D, E, F, G, R(49), 0x1E376C08);
952   P (G, H, A, B, C, D, E, F, R(50), 0x2748774C);
953   P (F, G, H, A, B, C, D, E, R(51), 0x34B0BCB5);
954   P (E, F, G, H, A, B, C, D, R(52), 0x391C0CB3);
955   P (D, E, F, G, H, A, B, C, R(53), 0x4ED8AA4A);
956   P (C, D, E, F, G, H, A, B, R(54), 0x5B9CCA4F);
957   P (B, C, D, E, F, G, H, A, R(55), 0x682E6FF3);
958   P (A, B, C, D, E, F, G, H, R(56), 0x748F82EE);
959   P (H, A, B, C, D, E, F, G, R(57), 0x78A5636F);
960   P (G, H, A, B, C, D, E, F, R(58), 0x84C87814);
961   P (F, G, H, A, B, C, D, E, R(59), 0x8CC70208);
962   P (E, F, G, H, A, B, C, D, R(60), 0x90BEFFFA);
963   P (D, E, F, G, H, A, B, C, R(61), 0xA4506CEB);
964   P (C, D, E, F, G, H, A, B, R(62), 0xBEF9A3F7);
965   P (B, C, D, E, F, G, H, A, R(63), 0xC67178F2);
966
967 #undef SHR
968 #undef ROTR
969 #undef S0
970 #undef S1
971 #undef S2
972 #undef S3
973 #undef F0
974 #undef F1
975 #undef R
976 #undef P
977
978   buf[0] += A;
979   buf[1] += B;
980   buf[2] += C;
981   buf[3] += D;
982   buf[4] += E;
983   buf[5] += F;
984   buf[6] += G;
985   buf[7] += H;
986 }
987
988 static void
989 sha256_sum_update (Sha256sum    *sha256,
990                    const guchar *buffer,
991                    gsize         length)
992 {
993   guint32 left, fill;
994   const guint8 *input = buffer;
995
996   if (length == 0)
997     return;
998
999   left = sha256->bits[0] & 0x3F;
1000   fill = 64 - left;
1001
1002   sha256->bits[0] += length;
1003   sha256->bits[0] &= 0xFFFFFFFF;
1004
1005   if (sha256->bits[0] < length)
1006       sha256->bits[1]++;
1007
1008   if (left > 0 && length >= fill)
1009     {
1010       memcpy ((sha256->data + left), input, fill);
1011
1012       sha256_transform (sha256->buf, sha256->data);
1013       length -= fill;
1014       input += fill;
1015
1016       left = 0;
1017     }
1018
1019   while (length >= SHA256_DATASIZE)
1020     {
1021       sha256_transform (sha256->buf, input);
1022
1023       length -= 64;
1024       input += 64;
1025     }
1026
1027   if (length)
1028     memcpy (sha256->data + left, input, length);
1029 }
1030
1031 static guint8 sha256_padding[64] =
1032 {
1033  0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1034     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1035     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
1036     0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0
1037 };
1038
1039 static void
1040 sha256_sum_close (Sha256sum *sha256)
1041 {
1042   guint32 last, padn;
1043   guint32 high, low;
1044   guint8 msglen[8];
1045
1046   high = (sha256->bits[0] >> 29)
1047        | (sha256->bits[1] <<  3);
1048   low  = (sha256->bits[0] <<  3);
1049
1050   PUT_UINT32 (high, msglen, 0);
1051   PUT_UINT32 (low, msglen, 4);
1052
1053   last = sha256->bits[0] & 0x3F;
1054   padn = (last < 56) ? (56 - last) : (120 - last);
1055
1056   sha256_sum_update (sha256, sha256_padding, padn);
1057   sha256_sum_update (sha256, msglen, 8);
1058
1059   PUT_UINT32 (sha256->buf[0], sha256->digest,  0);
1060   PUT_UINT32 (sha256->buf[1], sha256->digest,  4);
1061   PUT_UINT32 (sha256->buf[2], sha256->digest,  8);
1062   PUT_UINT32 (sha256->buf[3], sha256->digest, 12);
1063   PUT_UINT32 (sha256->buf[4], sha256->digest, 16);
1064   PUT_UINT32 (sha256->buf[5], sha256->digest, 20);
1065   PUT_UINT32 (sha256->buf[6], sha256->digest, 24);
1066   PUT_UINT32 (sha256->buf[7], sha256->digest, 28);
1067 }
1068
1069 #undef PUT_UINT32
1070 #undef GET_UINT32
1071
1072 static gchar *
1073 sha256_sum_to_string (Sha256sum *sha256)
1074 {
1075   return digest_to_string (sha256->digest, SHA256_DIGEST_LEN);
1076 }
1077
1078 static void
1079 sha256_sum_digest (Sha256sum *sha256,
1080                    guint8    *digest)
1081 {
1082   gint i;
1083
1084   for (i = 0; i < SHA256_DIGEST_LEN; i++)
1085     digest[i] = sha256->digest[i];
1086 }
1087
1088 /*
1089  * SHA-512 Checksum
1090  *
1091  * Implemented following FIPS-180-2 standard at
1092  * http://csrc.nist.gov/publications/fips/fips180-2/fips180-2.pdf.
1093  * References in the form [§x.y.z] map to sections in that document.
1094  *
1095  *   Author: Eduardo Lima Mitev <elima@igalia.com>
1096  */
1097
1098 /* SHA-384 and SHA-512 functions [§4.1.3] */
1099 #define Ch(x,y,z)  ((x & y) ^ (~x & z))
1100 #define Maj(x,y,z) ((x & y) ^ (x & z) ^ (y & z))
1101 #define SHR(n,x)   (x >> n)
1102 #define ROTR(n,x)  (SHR (n, x) | (x << (64 - n)))
1103 #define SIGMA0(x)  (ROTR (28, x) ^ ROTR (34, x) ^ ROTR (39, x))
1104 #define SIGMA1(x)  (ROTR (14, x) ^ ROTR (18, x) ^ ROTR (41, x))
1105 #define sigma0(x)  (ROTR ( 1, x) ^ ROTR ( 8, x) ^ SHR  ( 7, x))
1106 #define sigma1(x)  (ROTR (19, x) ^ ROTR (61, x) ^ SHR  ( 6, x))
1107
1108 #define PUT_UINT64(n,b,i)                G_STMT_START{   \
1109     (b)[(i)    ] = (guint8) (n >> 56);                   \
1110     (b)[(i) + 1] = (guint8) (n >> 48);                   \
1111     (b)[(i) + 2] = (guint8) (n >> 40);                   \
1112     (b)[(i) + 3] = (guint8) (n >> 32);                   \
1113     (b)[(i) + 4] = (guint8) (n >> 24);                   \
1114     (b)[(i) + 5] = (guint8) (n >> 16);                   \
1115     (b)[(i) + 6] = (guint8) (n >>  8);                   \
1116     (b)[(i) + 7] = (guint8) (n      ); } G_STMT_END
1117
1118 static void
1119 sha512_sum_init (Sha512sum *sha512)
1120 {
1121   /* Initial Hash Value [§5.3.4] */
1122   sha512->H[0] = 0x6a09e667f3bcc908;
1123   sha512->H[1] = 0xbb67ae8584caa73b;
1124   sha512->H[2] = 0x3c6ef372fe94f82b;
1125   sha512->H[3] = 0xa54ff53a5f1d36f1;
1126   sha512->H[4] = 0x510e527fade682d1;
1127   sha512->H[5] = 0x9b05688c2b3e6c1f;
1128   sha512->H[6] = 0x1f83d9abfb41bd6b;
1129   sha512->H[7] = 0x5be0cd19137e2179;
1130
1131   sha512->block_len = 0;
1132
1133   sha512->data_len[0] = 0;
1134   sha512->data_len[1] = 0;
1135 }
1136
1137 /* SHA-384 and SHA-512 constants [§4.2.3] */
1138 static const guint64 SHA512_K[80] = {
1139   0x428a2f98d728ae22, 0x7137449123ef65cd,
1140   0xb5c0fbcfec4d3b2f, 0xe9b5dba58189dbbc,
1141   0x3956c25bf348b538, 0x59f111f1b605d019,
1142   0x923f82a4af194f9b, 0xab1c5ed5da6d8118,
1143   0xd807aa98a3030242, 0x12835b0145706fbe,
1144   0x243185be4ee4b28c, 0x550c7dc3d5ffb4e2,
1145   0x72be5d74f27b896f, 0x80deb1fe3b1696b1,
1146   0x9bdc06a725c71235, 0xc19bf174cf692694,
1147   0xe49b69c19ef14ad2, 0xefbe4786384f25e3,
1148   0x0fc19dc68b8cd5b5, 0x240ca1cc77ac9c65,
1149   0x2de92c6f592b0275, 0x4a7484aa6ea6e483,
1150   0x5cb0a9dcbd41fbd4, 0x76f988da831153b5,
1151   0x983e5152ee66dfab, 0xa831c66d2db43210,
1152   0xb00327c898fb213f, 0xbf597fc7beef0ee4,
1153   0xc6e00bf33da88fc2, 0xd5a79147930aa725,
1154   0x06ca6351e003826f, 0x142929670a0e6e70,
1155   0x27b70a8546d22ffc, 0x2e1b21385c26c926,
1156   0x4d2c6dfc5ac42aed, 0x53380d139d95b3df,
1157   0x650a73548baf63de, 0x766a0abb3c77b2a8,
1158   0x81c2c92e47edaee6, 0x92722c851482353b,
1159   0xa2bfe8a14cf10364, 0xa81a664bbc423001,
1160   0xc24b8b70d0f89791, 0xc76c51a30654be30,
1161   0xd192e819d6ef5218, 0xd69906245565a910,
1162   0xf40e35855771202a, 0x106aa07032bbd1b8,
1163   0x19a4c116b8d2d0c8, 0x1e376c085141ab53,
1164   0x2748774cdf8eeb99, 0x34b0bcb5e19b48a8,
1165   0x391c0cb3c5c95a63, 0x4ed8aa4ae3418acb,
1166   0x5b9cca4f7763e373, 0x682e6ff3d6b2b8a3,
1167   0x748f82ee5defb2fc, 0x78a5636f43172f60,
1168   0x84c87814a1f0ab72, 0x8cc702081a6439ec,
1169   0x90befffa23631e28, 0xa4506cebde82bde9,
1170   0xbef9a3f7b2c67915, 0xc67178f2e372532b,
1171   0xca273eceea26619c, 0xd186b8c721c0c207,
1172   0xeada7dd6cde0eb1e, 0xf57d4f7fee6ed178,
1173   0x06f067aa72176fba, 0x0a637dc5a2c898a6,
1174   0x113f9804bef90dae, 0x1b710b35131c471b,
1175   0x28db77f523047d84, 0x32caab7b40c72493,
1176   0x3c9ebe0a15c9bebc, 0x431d67c49c100d4c,
1177   0x4cc5d4becb3e42b6, 0x597f299cfc657e2a,
1178   0x5fcb6fab3ad6faec, 0x6c44198c4a475817
1179 };
1180
1181 static void
1182 sha512_transform (guint64      H[8],
1183                   guint8 const data[SHA512_BLOCK_LEN])
1184 {
1185   gint i;
1186   gint t;
1187   guint64 a, b, c, d, e, f, g, h;
1188   guint64 M[16];
1189   guint64 W[80];
1190
1191   /* SHA-512 hash computation [§6.3.2] */
1192
1193   /* prepare the message schedule */
1194   for (i = 0; i < 16; i++)
1195     {
1196       gint p = i * 8;
1197
1198       M[i] =
1199         ((guint64) data[p + 0] << 56) |
1200         ((guint64) data[p + 1] << 48) |
1201         ((guint64) data[p + 2] << 40) |
1202         ((guint64) data[p + 3] << 32) |
1203         ((guint64) data[p + 4] << 24) |
1204         ((guint64) data[p + 5] << 16) |
1205         ((guint64) data[p + 6] <<  8) |
1206         ((guint64) data[p + 7]      );
1207     }
1208
1209   for (t = 0; t < 80; t++)
1210     if (t < 16)
1211       W[t] = M[t];
1212     else
1213       W[t] = sigma1 (W[t - 2]) + W[t - 7] + sigma0 (W[t - 15]) + W[t - 16];
1214
1215   /* initialize the eight working variables */
1216   a = H[0];
1217   b = H[1];
1218   c = H[2];
1219   d = H[3];
1220   e = H[4];
1221   f = H[5];
1222   g = H[6];
1223   h = H[7];
1224
1225   for (t = 0; t < 80; t++)
1226     {
1227       guint64 T1, T2;
1228
1229       T1 = h + SIGMA1 (e) + Ch (e, f, g) + SHA512_K[t] + W[t];
1230       T2 = SIGMA0 (a) + Maj (a, b, c);
1231       h = g;
1232       g = f;
1233       f = e;
1234       e = d + T1;
1235       d = c;
1236       c = b;
1237       b = a;
1238       a = T1 + T2;
1239     }
1240
1241   /* Compute the intermediate hash value H */
1242   H[0] += a;
1243   H[1] += b;
1244   H[2] += c;
1245   H[3] += d;
1246   H[4] += e;
1247   H[5] += f;
1248   H[6] += g;
1249   H[7] += h;
1250 }
1251
1252 static void
1253 sha512_sum_update (Sha512sum    *sha512,
1254                    const guchar *buffer,
1255                    gsize         length)
1256 {
1257   gsize block_left, offset = 0;
1258
1259   if (length == 0)
1260     return;
1261
1262   sha512->data_len[0] += length * 8;
1263   if (sha512->data_len[0] < length)
1264     sha512->data_len[1]++;
1265
1266   /* try to fill current block */
1267   block_left = SHA512_BLOCK_LEN - sha512->block_len;
1268   if (block_left > 0)
1269     {
1270       gsize fill_len;
1271
1272       fill_len = MIN (block_left, length);
1273       memcpy (sha512->block + sha512->block_len, buffer, fill_len);
1274       sha512->block_len += fill_len;
1275       length -= fill_len;
1276       offset += fill_len;
1277
1278       if (sha512->block_len == SHA512_BLOCK_LEN)
1279         {
1280           sha512_transform (sha512->H, sha512->block);
1281           sha512->block_len = 0;
1282         }
1283     }
1284
1285   /* process complete blocks */
1286   while (length >= SHA512_BLOCK_LEN)
1287     {
1288       memcpy (sha512->block, buffer + offset, SHA512_BLOCK_LEN);
1289
1290       sha512_transform (sha512->H, sha512->block);
1291
1292       length -= SHA512_BLOCK_LEN;
1293       offset += SHA512_BLOCK_LEN;
1294     }
1295
1296   /* keep remaining data for next block */
1297   if (length > 0)
1298     {
1299       memcpy (sha512->block, buffer + offset, length);
1300       sha512->block_len = length;
1301     }
1302 }
1303
1304 static void
1305 sha512_sum_close (Sha512sum *sha512)
1306 {
1307   guint l;
1308   gint zeros;
1309   guint8 pad[SHA512_BLOCK_LEN * 2] = { 0, };
1310   guint pad_len = 0;
1311   gint i;
1312
1313   /* apply padding [§5.1.2] */
1314   l = sha512->block_len * 8;
1315   zeros = 896 - (l + 1);
1316
1317   if (zeros < 0)
1318     zeros += 128 * 8;
1319
1320   pad[0] = 0x80; /* 1000 0000 */
1321   zeros -= 7;
1322   pad_len++;
1323
1324   memset (pad + pad_len, 0x00, zeros / 8);
1325   pad_len += zeros / 8;
1326   zeros = zeros % 8;
1327
1328   /* put message bit length at the end of padding */
1329   PUT_UINT64 (sha512->data_len[1], pad, pad_len);
1330   pad_len += 8;
1331
1332   PUT_UINT64 (sha512->data_len[0], pad, pad_len);
1333   pad_len += 8;
1334
1335   /* update checksum with the padded block */
1336   sha512_sum_update (sha512, pad, pad_len);
1337
1338   /* copy resulting 64-bit words into digest */
1339   for (i = 0; i < 8; i++)
1340     PUT_UINT64 (sha512->H[i], sha512->digest, i * 8);
1341 }
1342
1343 static gchar *
1344 sha512_sum_to_string (Sha512sum *sha512)
1345 {
1346   return digest_to_string (sha512->digest, SHA512_DIGEST_LEN);
1347 }
1348
1349 static void
1350 sha512_sum_digest (Sha512sum *sha512,
1351                    guint8    *digest)
1352 {
1353   memcpy (digest, sha512->digest, SHA512_DIGEST_LEN);
1354 }
1355
1356 #undef Ch
1357 #undef Maj
1358 #undef SHR
1359 #undef ROTR
1360 #undef SIGMA0
1361 #undef SIGMA1
1362 #undef sigma0
1363 #undef sigma1
1364
1365 #undef PUT_UINT64
1366
1367 /*
1368  * Public API
1369  */
1370
1371 /**
1372  * g_checksum_type_get_length:
1373  * @checksum_type: a #GChecksumType
1374  *
1375  * Gets the length in bytes of digests of type @checksum_type
1376  *
1377  * Return value: the checksum length, or -1 if @checksum_type is
1378  * not supported.
1379  *
1380  * Since: 2.16
1381  */
1382 gssize
1383 g_checksum_type_get_length (GChecksumType checksum_type)
1384 {
1385   gssize len = -1;
1386
1387   switch (checksum_type)
1388     {
1389     case G_CHECKSUM_MD5:
1390       len = MD5_DIGEST_LEN;
1391       break;
1392     case G_CHECKSUM_SHA1:
1393       len = SHA1_DIGEST_LEN;
1394       break;
1395     case G_CHECKSUM_SHA256:
1396       len = SHA256_DIGEST_LEN;
1397       break;
1398     case G_CHECKSUM_SHA512:
1399       len = SHA512_DIGEST_LEN;
1400       break;
1401     default:
1402       len = -1;
1403       break;
1404     }
1405
1406   return len;
1407 }
1408
1409 /**
1410  * g_checksum_new:
1411  * @checksum_type: the desired type of checksum
1412  *
1413  * Creates a new #GChecksum, using the checksum algorithm @checksum_type.
1414  * If the @checksum_type is not known, %NULL is returned.
1415  * A #GChecksum can be used to compute the checksum, or digest, of an
1416  * arbitrary binary blob, using different hashing algorithms.
1417  *
1418  * A #GChecksum works by feeding a binary blob through g_checksum_update()
1419  * until there is data to be checked; the digest can then be extracted
1420  * using g_checksum_get_string(), which will return the checksum as a
1421  * hexadecimal string; or g_checksum_get_digest(), which will return a
1422  * vector of raw bytes. Once either g_checksum_get_string() or
1423  * g_checksum_get_digest() have been called on a #GChecksum, the checksum
1424  * will be closed and it won't be possible to call g_checksum_update()
1425  * on it anymore.
1426  *
1427  * Return value: (transfer full): the newly created #GChecksum, or %NULL.
1428  *   Use g_checksum_free() to free the memory allocated by it.
1429  *
1430  * Since: 2.16
1431  */
1432 GChecksum *
1433 g_checksum_new (GChecksumType checksum_type)
1434 {
1435   GChecksum *checksum;
1436
1437   if (! IS_VALID_TYPE (checksum_type))
1438     return NULL;
1439
1440   checksum = g_slice_new0 (GChecksum);
1441   checksum->type = checksum_type;
1442
1443   g_checksum_reset (checksum);
1444
1445   return checksum;
1446 }
1447
1448 /**
1449  * g_checksum_reset:
1450  * @checksum: the #GChecksum to reset
1451  *
1452  * Resets the state of the @checksum back to its initial state.
1453  *
1454  * Since: 2.18
1455  **/
1456 void
1457 g_checksum_reset (GChecksum *checksum)
1458 {
1459   g_return_if_fail (checksum != NULL);
1460
1461   g_free (checksum->digest_str);
1462   checksum->digest_str = NULL;
1463
1464   switch (checksum->type)
1465     {
1466     case G_CHECKSUM_MD5:
1467       md5_sum_init (&(checksum->sum.md5));
1468       break;
1469     case G_CHECKSUM_SHA1:
1470       sha1_sum_init (&(checksum->sum.sha1));
1471       break;
1472     case G_CHECKSUM_SHA256:
1473       sha256_sum_init (&(checksum->sum.sha256));
1474       break;
1475     case G_CHECKSUM_SHA512:
1476       sha512_sum_init (&(checksum->sum.sha512));
1477       break;
1478     default:
1479       g_assert_not_reached ();
1480       break;
1481     }
1482 }
1483
1484 /**
1485  * g_checksum_copy:
1486  * @checksum: the #GChecksum to copy
1487  *
1488  * Copies a #GChecksum. If @checksum has been closed, by calling
1489  * g_checksum_get_string() or g_checksum_get_digest(), the copied
1490  * checksum will be closed as well.
1491  *
1492  * Return value: the copy of the passed #GChecksum. Use g_checksum_free()
1493  *   when finished using it.
1494  *
1495  * Since: 2.16
1496  */
1497 GChecksum *
1498 g_checksum_copy (const GChecksum *checksum)
1499 {
1500   GChecksum *copy;
1501
1502   g_return_val_if_fail (checksum != NULL, NULL);
1503
1504   copy = g_slice_new (GChecksum);
1505   *copy = *checksum;
1506
1507   copy->digest_str = g_strdup (checksum->digest_str);
1508
1509   return copy;
1510 }
1511
1512 /**
1513  * g_checksum_free:
1514  * @checksum: a #GChecksum
1515  *
1516  * Frees the memory allocated for @checksum.
1517  *
1518  * Since: 2.16
1519  */
1520 void
1521 g_checksum_free (GChecksum *checksum)
1522 {
1523   if (G_LIKELY (checksum))
1524     {
1525       g_free (checksum->digest_str);
1526
1527       g_slice_free (GChecksum, checksum);
1528     }
1529 }
1530
1531 /**
1532  * g_checksum_update:
1533  * @checksum: a #GChecksum
1534  * @data: (array length=length) (element-type guint8): buffer used to compute the checksum
1535  * @length: size of the buffer, or -1 if it is a null-terminated string.
1536  *
1537  * Feeds @data into an existing #GChecksum. The checksum must still be
1538  * open, that is g_checksum_get_string() or g_checksum_get_digest() must
1539  * not have been called on @checksum.
1540  *
1541  * Since: 2.16
1542  */
1543 void
1544 g_checksum_update (GChecksum    *checksum,
1545                    const guchar *data,
1546                    gssize        length)
1547 {
1548   g_return_if_fail (checksum != NULL);
1549   g_return_if_fail (length == 0 || data != NULL);
1550
1551   if (length < 0)
1552     length = strlen ((const gchar *) data);
1553
1554   if (checksum->digest_str)
1555     {
1556       g_warning ("The checksum `%s' has been closed and cannot be updated "
1557                  "anymore.",
1558                  checksum->digest_str);
1559       return;
1560     }
1561
1562   switch (checksum->type)
1563     {
1564     case G_CHECKSUM_MD5:
1565       md5_sum_update (&(checksum->sum.md5), data, length);
1566       break;
1567     case G_CHECKSUM_SHA1:
1568       sha1_sum_update (&(checksum->sum.sha1), data, length);
1569       break;
1570     case G_CHECKSUM_SHA256:
1571       sha256_sum_update (&(checksum->sum.sha256), data, length);
1572       break;
1573     case G_CHECKSUM_SHA512:
1574       sha512_sum_update (&(checksum->sum.sha512), data, length);
1575       break;
1576     default:
1577       g_assert_not_reached ();
1578       break;
1579     }
1580 }
1581
1582 /**
1583  * g_checksum_get_string:
1584  * @checksum: a #GChecksum
1585  *
1586  * Gets the digest as an hexadecimal string.
1587  *
1588  * Once this function has been called the #GChecksum can no longer be
1589  * updated with g_checksum_update().
1590  *
1591  * The hexadecimal characters will be lower case.
1592  *
1593  * Return value: the hexadecimal representation of the checksum. The
1594  *   returned string is owned by the checksum and should not be modified
1595  *   or freed.
1596  *
1597  * Since: 2.16
1598  */
1599 const gchar *
1600 g_checksum_get_string (GChecksum *checksum)
1601 {
1602   gchar *str = NULL;
1603
1604   g_return_val_if_fail (checksum != NULL, NULL);
1605
1606   if (checksum->digest_str)
1607     return checksum->digest_str;
1608
1609   switch (checksum->type)
1610     {
1611     case G_CHECKSUM_MD5:
1612       md5_sum_close (&(checksum->sum.md5));
1613       str = md5_sum_to_string (&(checksum->sum.md5));
1614       break;
1615     case G_CHECKSUM_SHA1:
1616       sha1_sum_close (&(checksum->sum.sha1));
1617       str = sha1_sum_to_string (&(checksum->sum.sha1));
1618       break;
1619     case G_CHECKSUM_SHA256:
1620       sha256_sum_close (&(checksum->sum.sha256));
1621       str = sha256_sum_to_string (&(checksum->sum.sha256));
1622       break;
1623     case G_CHECKSUM_SHA512:
1624       sha512_sum_close (&(checksum->sum.sha512));
1625       str = sha512_sum_to_string (&(checksum->sum.sha512));
1626       break;
1627     default:
1628       g_assert_not_reached ();
1629       break;
1630     }
1631
1632   checksum->digest_str = str;
1633
1634   return checksum->digest_str;
1635 }
1636
1637 /**
1638  * g_checksum_get_digest: (skip)
1639  * @checksum: a #GChecksum
1640  * @buffer: output buffer
1641  * @digest_len: an inout parameter. The caller initializes it to the size of @buffer.
1642  *   After the call it contains the length of the digest.
1643  *
1644  * Gets the digest from @checksum as a raw binary vector and places it
1645  * into @buffer. The size of the digest depends on the type of checksum.
1646  *
1647  * Once this function has been called, the #GChecksum is closed and can
1648  * no longer be updated with g_checksum_update().
1649  *
1650  * Since: 2.16
1651  */
1652 void
1653 g_checksum_get_digest (GChecksum  *checksum,
1654                        guint8     *buffer,
1655                        gsize      *digest_len)
1656 {
1657   gboolean checksum_open = FALSE;
1658   gchar *str = NULL;
1659   gsize len;
1660
1661   g_return_if_fail (checksum != NULL);
1662
1663   len = g_checksum_type_get_length (checksum->type);
1664   g_return_if_fail (*digest_len >= len);
1665
1666   checksum_open = !!(checksum->digest_str == NULL);
1667
1668   switch (checksum->type)
1669     {
1670     case G_CHECKSUM_MD5:
1671       if (checksum_open)
1672         {
1673           md5_sum_close (&(checksum->sum.md5));
1674           str = md5_sum_to_string (&(checksum->sum.md5));
1675         }
1676       md5_sum_digest (&(checksum->sum.md5), buffer);
1677       break;
1678     case G_CHECKSUM_SHA1:
1679       if (checksum_open)
1680         {
1681           sha1_sum_close (&(checksum->sum.sha1));
1682           str = sha1_sum_to_string (&(checksum->sum.sha1));
1683         }
1684       sha1_sum_digest (&(checksum->sum.sha1), buffer);
1685       break;
1686     case G_CHECKSUM_SHA256:
1687       if (checksum_open)
1688         {
1689           sha256_sum_close (&(checksum->sum.sha256));
1690           str = sha256_sum_to_string (&(checksum->sum.sha256));
1691         }
1692       sha256_sum_digest (&(checksum->sum.sha256), buffer);
1693       break;
1694     case G_CHECKSUM_SHA512:
1695       if (checksum_open)
1696         {
1697           sha512_sum_close (&(checksum->sum.sha512));
1698           str = sha512_sum_to_string (&(checksum->sum.sha512));
1699         }
1700       sha512_sum_digest (&(checksum->sum.sha512), buffer);
1701       break;
1702     default:
1703       g_assert_not_reached ();
1704       break;
1705     }
1706
1707   if (str)
1708     checksum->digest_str = str;
1709
1710   *digest_len = len;
1711 }
1712
1713 /**
1714  * g_compute_checksum_for_data:
1715  * @checksum_type: a #GChecksumType
1716  * @data: (array length=length) (element-type guint8): binary blob to compute the digest of
1717  * @length: length of @data
1718  *
1719  * Computes the checksum for a binary @data of @length. This is a
1720  * convenience wrapper for g_checksum_new(), g_checksum_get_string()
1721  * and g_checksum_free().
1722  *
1723  * The hexadecimal string returned will be in lower case.
1724  *
1725  * Return value: the digest of the binary data as a string in hexadecimal.
1726  *   The returned string should be freed with g_free() when done using it.
1727  *
1728  * Since: 2.16
1729  */
1730 gchar *
1731 g_compute_checksum_for_data (GChecksumType  checksum_type,
1732                              const guchar  *data,
1733                              gsize          length)
1734 {
1735   GChecksum *checksum;
1736   gchar *retval;
1737
1738   g_return_val_if_fail (IS_VALID_TYPE (checksum_type), NULL);
1739   g_return_val_if_fail (length == 0 || data != NULL, NULL);
1740
1741   checksum = g_checksum_new (checksum_type);
1742   if (!checksum)
1743     return NULL;
1744
1745   g_checksum_update (checksum, data, length);
1746   retval = g_strdup (g_checksum_get_string (checksum));
1747   g_checksum_free (checksum);
1748
1749   return retval;
1750 }
1751
1752 /**
1753  * g_compute_checksum_for_string:
1754  * @checksum_type: a #GChecksumType
1755  * @str: the string to compute the checksum of
1756  * @length: the length of the string, or -1 if the string is null-terminated.
1757  *
1758  * Computes the checksum of a string.
1759  *
1760  * The hexadecimal string returned will be in lower case.
1761  *
1762  * Return value: the checksum as a hexadecimal string. The returned string
1763  *   should be freed with g_free() when done using it.
1764  *
1765  * Since: 2.16
1766  */
1767 gchar *
1768 g_compute_checksum_for_string (GChecksumType  checksum_type,
1769                                const gchar   *str,
1770                                gssize         length)
1771 {
1772   g_return_val_if_fail (IS_VALID_TYPE (checksum_type), NULL);
1773   g_return_val_if_fail (length == 0 || str != NULL, NULL);
1774
1775   if (length < 0)
1776     length = strlen (str);
1777
1778   return g_compute_checksum_for_data (checksum_type, (const guchar *) str, length);
1779 }
1780
1781 /**
1782  * g_compute_checksum_for_bytes:
1783  * @checksum_type: a #GChecksumType
1784  * @data: binary blob to compute the digest of
1785  *
1786  * Computes the checksum for a binary @data. This is a
1787  * convenience wrapper for g_checksum_new(), g_checksum_get_string()
1788  * and g_checksum_free().
1789  *
1790  * The hexadecimal string returned will be in lower case.
1791  *
1792  * Return value: the digest of the binary data as a string in hexadecimal.
1793  *   The returned string should be freed with g_free() when done using it.
1794  *
1795  * Since: 2.34
1796  */
1797 gchar *
1798 g_compute_checksum_for_bytes (GChecksumType  checksum_type,
1799                               GBytes        *data)
1800 {
1801   gconstpointer byte_data;
1802   gsize length;
1803
1804   g_return_val_if_fail (IS_VALID_TYPE (checksum_type), NULL);
1805   g_return_val_if_fail (data != NULL, NULL);
1806
1807   byte_data = g_bytes_get_data (data, &length);
1808   return g_compute_checksum_for_data (checksum_type, byte_data, length);
1809 }