hmac: Implementation of HMAC in glib
[platform/upstream/glib.git] / glib / ghmac.c
1 /* ghmac.h - data hashing functions
2  *
3  * Copyright (C) 2011  Collabora Ltd.
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  * Author: Stef Walter <stefw@collabora.co.uk>
21  */
22
23 #include "config.h"
24
25 #include <string.h>
26
27 #include "ghmac.h"
28
29 #include "glib/galloca.h"
30 #include "gatomic.h"
31 #include "gmem.h"
32 #include "gstrfuncs.h"
33 #include "gtestutils.h"
34 #include "gtypes.h"
35 #include "glibintl.h"
36
37
38 /**
39  * SECTION:hmac
40  * @title: Secure HMAC Digests
41  * @short_description: Computes the HMAC for data
42  *
43  * HMACs should be used when producing a cookie or hash based on data and a key.
44  * Simple mechanisms for using SHA1 and other algorithms to digest a key and
45  * data together are vulnerable to various security issues. HMAC uses algorithms
46  * like SHA1 in a secure way to produce a digest of a key and data.
47  *
48  * Both the key and data are arbitrary byte arrays of bytes or characters.
49  *
50  * Support for HMAC Digests has been added in GLib 2.30
51  **/
52
53 struct _GHmac
54 {
55   int ref_count;
56   GChecksumType digest_type;
57   GChecksum *digesti;
58   GChecksum *digesto;
59 };
60
61 /**
62  * g_hmac_new:
63  * @digest_type: the desired type of digest
64  * @key: (array length=key_len): the key for the HMAC
65  * @key_len: the length of the keys
66  *
67  * Creates a new #GHmac, using the digest algorithm @digest_type.
68  * If the @digest_type is not known, %NULL is returned.
69  * A #GHmac can be used to compute the HMAC of a key and an
70  * arbitrary binary blob, using different hashing algorithms.
71  *
72  * A #GHmac works by feeding a binary blob through g_hmac_update()
73  * until the data is complete; the digest can then be extracted
74  * using g_hmac_get_string(), which will return the checksum as a
75  * hexadecimal string; or g_hmac_get_digest(), which will return a
76  * array of raw bytes. Once either g_hmac_get_string() or
77  * g_hmac_get_digest() have been called on a #GHmac, the HMAC
78  * will be closed and it won't be possible to call g_hmac_update()
79  * on it anymore.
80  *
81  * Return value: the newly created #GHmac, or %NULL.
82  *   Use g_hmac_unref() to free the memory allocated by it.
83  *
84  * Since: 2.30
85  */
86 GHmac *
87 g_hmac_new (GChecksumType  digest_type,
88             const guchar  *key,
89             gsize          key_len)
90 {
91   GChecksum *checksum;
92   GHmac *hmac;
93   guchar *buffer;
94   guchar *pad;
95   gsize i, len;
96   gsize block_size;
97
98   checksum = g_checksum_new (digest_type);
99   g_return_val_if_fail (checksum != NULL, NULL);
100
101   switch (digest_type)
102     {
103     case G_CHECKSUM_MD5:
104     case G_CHECKSUM_SHA1:
105       block_size = 64; /* RFC 2104 */
106       break;
107     case G_CHECKSUM_SHA256:
108       block_size = 64; /* RFC draft-kelly-ipsec-ciph-sha2-01 */
109       break;
110     default:
111       g_return_val_if_reached (NULL);
112     }
113
114   hmac = g_slice_new0 (GHmac);
115   hmac->ref_count = 1;
116   hmac->digest_type = digest_type;
117   hmac->digesti = checksum;
118   hmac->digesto = g_checksum_new (digest_type);
119
120   buffer = g_alloca (block_size);
121   pad = g_alloca (block_size);
122
123   memset (buffer, 0, block_size);
124
125   /* If the key is too long, hash it */
126   if (key_len > block_size)
127     {
128       len = block_size;
129       g_checksum_update (hmac->digesti, key, key_len);
130       g_checksum_get_digest (hmac->digesti, buffer, &len);
131       g_checksum_reset (hmac->digesti);
132     }
133
134   /* Otherwise pad it with zeros */
135   else
136     {
137       memcpy (buffer, key, key_len);
138     }
139
140   /* First pad */
141   for (i = 0; i < block_size; i++)
142     pad[i] = 0x36 ^ buffer[i]; /* ipad value */
143   g_checksum_update (hmac->digesti, pad, block_size);
144
145   /* Second pad */
146   for (i = 0; i < block_size; i++)
147     pad[i] = 0x5c ^ buffer[i]; /* opad value */
148   g_checksum_update (hmac->digesto, pad, block_size);
149
150   return hmac;
151 }
152
153 /**
154  * g_hmac_copy:
155  * @hmac: the #GHmac to copy
156  *
157  * Copies a #GHmac. If @hmac has been closed, by calling
158  * g_hmac_get_string() or g_hmac_get_digest(), the copied
159  * HMAC will be closed as well.
160  *
161  * Return value: the copy of the passed #GHmac. Use g_hmac_unref()
162  *   when finished using it.
163  *
164  * Since: 2.30
165  */
166 GHmac *
167 g_hmac_copy (const GHmac *hmac)
168 {
169   GHmac *copy;
170
171   g_return_val_if_fail (hmac != NULL, NULL);
172
173   copy = g_slice_new (GHmac);
174   copy->digest_type = hmac->digest_type;
175   copy->digesti = g_checksum_copy (hmac->digesti);
176   copy->digesto = g_checksum_copy (hmac->digesto);
177
178   return copy;
179 }
180
181 /**
182  * g_hmac_ref:
183  * @hmac: a valid #GHmac.
184  *
185  * Atomically increments the reference count of @hmac by one.
186  * This function is MT-safe and may be called from any thread.
187  *
188  * Return value: the passed in #GHmac.
189  *
190  * Since: 2.30
191  **/
192 GHmac *
193 g_hmac_ref (GHmac *hmac)
194 {
195   g_return_val_if_fail (hmac != NULL, NULL);
196
197   g_atomic_int_inc (&hmac->ref_count);
198
199   return hmac;
200 }
201
202 /**
203  * g_hmac_unref:
204  * @hmac: a #GHmac
205  *
206  * Atomically decrements the reference count of @hmac by one.
207  * If the reference count drops to 0, all keys and values will be
208  * destroyed, and all memory allocated by the hash table is released.
209  * This function is MT-safe and may be called from any thread.
210  * Frees the memory allocated for @hmac.
211  *
212  * Since: 2.30
213  */
214 void
215 g_hmac_unref (GHmac *hmac)
216 {
217   g_return_if_fail (hmac != NULL);
218
219   if (g_atomic_int_dec_and_test (&hmac->ref_count))
220     {
221       g_checksum_free (hmac->digesti);
222       g_checksum_free (hmac->digesto);
223       g_slice_free (GHmac, hmac);
224     }
225 }
226
227 /**
228  * g_hmac_update:
229  * @hmac: a #GHmac
230  * @data: (array length=length): buffer used to compute the checksum
231  * @length: size of the buffer, or -1 if it is a null-terminated string.
232  *
233  * Feeds @data into an existing #GHmac. The HMAC must still be
234  * open, that is g_hmac_get_string() or g_hmac_get_digest() must
235  * not have been called on @hmac.
236  *
237  * Since: 2.30
238  */
239 void
240 g_hmac_update (GHmac        *hmac,
241                const guchar *data,
242                gssize        length)
243 {
244   g_return_if_fail (hmac != NULL);
245   g_return_if_fail (length == 0 || data != NULL);
246
247   g_checksum_update (hmac->digesti, data, length);
248 }
249
250 /**
251  * g_hmac_get_string:
252  * @hmac: a #GHmac
253  *
254  * Gets the HMAC as an hexadecimal string.
255  *
256  * Once this function has been called the #GHmac can no longer be
257  * updated with g_hmac_update().
258  *
259  * The hexadecimal characters will be lower case.
260  *
261  * Return value: the hexadecimal representation of the HMAC. The
262  *   returned string is owned by the HMAC and should not be modified
263  *   or freed.
264  *
265  * Since: 2.30
266  */
267 const gchar *
268 g_hmac_get_string (GHmac *hmac)
269 {
270   guint8 *buffer;
271   gsize digest_len;
272
273   g_return_val_if_fail (hmac != NULL, NULL);
274
275   digest_len = g_checksum_type_get_length (hmac->digest_type);
276   buffer = g_malloc (digest_len);
277
278   g_hmac_get_digest (hmac, buffer, &digest_len);
279   return g_checksum_get_string (hmac->digesto);
280 }
281
282 /**
283  * g_checksum_get_digest:
284  * @hmac: a #GHmac
285  * @buffer: output buffer
286  * @digest_len: an inout parameter. The caller initializes it to the size of @buffer.
287  *   After the call it contains the length of the digest.
288  *
289  * Gets the digest from @checksum as a raw binary array and places it
290  * into @buffer. The size of the digest depends on the type of checksum.
291  *
292  * Once this function has been called, the #GHmac is closed and can
293  * no longer be updated with g_checksum_update().
294  *
295  * Since: 2.30
296  */
297 void
298 g_hmac_get_digest (GHmac      *hmac,
299                    guint8     *buffer,
300                    gsize      *digest_len)
301 {
302   gsize len;
303
304   g_return_if_fail (hmac != NULL);
305
306   len = g_checksum_type_get_length (hmac->digest_type);
307   g_return_if_fail (*digest_len >= len);
308
309   /* Use the same buffer, because we can :) */
310   g_checksum_get_digest (hmac->digesti, buffer, &len);
311   g_checksum_update (hmac->digesto, buffer, len);
312   g_checksum_get_digest (hmac->digesto, buffer, digest_len);
313 }
314
315 /**
316  * g_compute_hmac_for_data:
317  * @digest_type: a #GChecksumType to use for the HMAC
318  * @key: (array length=key_len): the key to use in the HMAC
319  * @key_len: the length of the key
320  * @data: binary blob to compute the HMAC of
321  * @length: length of @data
322  *
323  * Computes the HMAC for a binary @data of @length. This is a
324  * convenience wrapper for g_hmac_new(), g_hmac_get_string()
325  * and g_hmac_unref().
326  *
327  * The hexadecimal string returned will be in lower case.
328  *
329  * Return value: the HMAC of the binary data as a string in hexadecimal.
330  *   The returned string should be freed with g_free() when done using it.
331  *
332  * Since: 2.30
333  */
334 gchar *
335 g_compute_hmac_for_data (GChecksumType  digest_type,
336                          const guchar  *key,
337                          gsize          key_len,
338                          const guchar  *data,
339                          gsize          length)
340 {
341   GHmac *hmac;
342   gchar *retval;
343
344   g_return_val_if_fail (length == 0 || data != NULL, NULL);
345
346   hmac = g_hmac_new (digest_type, key, key_len);
347   if (!hmac)
348     return NULL;
349
350   g_hmac_update (hmac, data, length);
351   retval = g_strdup (g_hmac_get_string (hmac));
352   g_hmac_unref (hmac);
353
354   return retval;
355 }
356
357 /**
358  * g_compute_hmac_for_string:
359  * @digest_type: a #GChecksumType to use for the HMAC
360  * @key: (array length=key_len): the key to use in the HMAC
361  * @key_len: the length of the key
362  * @str: the string to compute the HMAC for
363  * @length: the length of the string, or -1 if the string is null-terminated.
364  *
365  * Computes the HMAC for a string.
366  *
367  * The hexadecimal string returned will be in lower case.
368  *
369  * Return value: the HMAC as a hexadecimal string. The returned string
370  *   should be freed with g_free() when done using it.
371  *
372  * Since: 2.30
373  */
374 gchar *
375 g_compute_hmac_for_string (GChecksumType  digest_type,
376                            const guchar  *key,
377                            gsize          key_len,
378                            const gchar   *str,
379                            gssize         length)
380 {
381   g_return_val_if_fail (length == 0 || str != NULL, NULL);
382
383   if (length < 0)
384     length = strlen (str);
385
386   return g_compute_hmac_for_data (digest_type, key, key_len,
387                                   (const guchar *) str, length);
388 }