resetting manifest requested domain to floor
[platform/upstream/nettle.git] / pbkdf2.c
1 /* pbkdf2.c
2  *
3  * PKCS #5 password-based key derivation function PBKDF2, see RFC 2898.
4  */
5
6 /* nettle, low-level cryptographics library
7  *
8  * Copyright (C) 2012 Simon Josefsson, Niels Möller
9  *
10  * The nettle library is free software; you can redistribute it and/or modify
11  * it under the terms of the GNU Lesser General Public License as published by
12  * the Free Software Foundation; either version 2.1 of the License, or (at your
13  * option) any later version.
14  *
15  * The nettle library is distributed in the hope that it will be useful, but
16  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
17  * or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU Lesser General Public
18  * License for more details.
19  *
20  * You should have received a copy of the GNU Lesser General Public License
21  * along with the nettle library; see the file COPYING.LIB.  If not, write to
22  * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
23  * MA 02111-1301, USA.
24  */
25
26 #if HAVE_CONFIG_H
27 # include "config.h"
28 #endif
29
30 #include <assert.h>
31 #include <stdlib.h>
32 #include <string.h>
33
34 #include "pbkdf2.h"
35
36 #include "macros.h"
37 #include "memxor.h"
38 #include "nettle-internal.h"
39
40 void
41 pbkdf2 (void *mac_ctx,
42         nettle_hash_update_func *update,
43         nettle_hash_digest_func *digest,
44         unsigned digest_size, unsigned iterations,
45         unsigned salt_length, const uint8_t *salt,
46         unsigned length, uint8_t *dst)
47 {
48   TMP_DECL(U, uint8_t, NETTLE_MAX_HASH_DIGEST_SIZE);
49   TMP_DECL(T, uint8_t, NETTLE_MAX_HASH_DIGEST_SIZE);
50   
51   unsigned i;
52
53   assert (iterations > 0);
54
55   if (length == 0)
56     return;
57
58   TMP_ALLOC (U, digest_size);
59   TMP_ALLOC (T, digest_size);
60
61   for (i = 1;;
62        i++, dst += digest_size, length -= digest_size)
63     {
64       uint8_t tmp[4];
65       uint8_t *prev;
66       unsigned u;
67       
68       WRITE_UINT32 (tmp, i);
69       
70       update (mac_ctx, salt_length, salt);
71       update (mac_ctx, sizeof(tmp), tmp);
72       digest (mac_ctx, digest_size, T);
73
74       prev = T;
75       
76       for (u = 1; u < iterations; u++, prev = U)
77         {
78           update (mac_ctx, digest_size, prev);
79           digest (mac_ctx, digest_size, U);
80
81           memxor (T, U, digest_size);
82         }
83
84       if (length <= digest_size)
85         {
86           memcpy (dst, T, length);
87           return;
88         }
89       memcpy (dst, T, digest_size);
90     }
91 }