Fix BSD license name
[platform/upstream/libgcrypt.git] / cipher / kdf.c
1 /* kdf.c  - Key Derivation Functions
2  * Copyright (C) 1998, 2011 Free Software Foundation, Inc.
3  * Copyright (C) 2013 g10 Code GmbH
4  *
5  * This file is part of Libgcrypt.
6  *
7  * Libgcrypt is free software; you can redistribute it and/or modify
8  * it under the terms of the GNU Lesser general Public License as
9  * published by the Free Software Foundation; either version 2.1 of
10  * the License, or (at your option) any later version.
11  *
12  * Libgcrypt is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
15  * GNU Lesser General Public License for more details.
16  *
17  * You should have received a copy of the GNU Lesser General Public
18  * License along with this program; if not, see <http://www.gnu.org/licenses/>.
19  */
20
21 #include <config.h>
22 #include <stdio.h>
23 #include <stdlib.h>
24 #include <string.h>
25 #include <errno.h>
26
27 #include "g10lib.h"
28 #include "cipher.h"
29 #include "ath.h"
30 #include "kdf-internal.h"
31
32
33 /* Transform a passphrase into a suitable key of length KEYSIZE and
34    store this key in the caller provided buffer KEYBUFFER.  The caller
35    must provide an HASHALGO, a valid ALGO and depending on that algo a
36    SALT of 8 bytes and the number of ITERATIONS.  Code taken from
37    gnupg/agent/protect.c:hash_passphrase.  */
38 static gpg_err_code_t
39 openpgp_s2k (const void *passphrase, size_t passphraselen,
40              int algo, int hashalgo,
41              const void *salt, size_t saltlen,
42              unsigned long iterations,
43              size_t keysize, void *keybuffer)
44 {
45   gpg_err_code_t ec;
46   gcry_md_hd_t md;
47   char *key = keybuffer;
48   int pass, i;
49   int used = 0;
50   int secmode;
51
52   if ((algo == GCRY_KDF_SALTED_S2K || algo == GCRY_KDF_ITERSALTED_S2K)
53       && (!salt || saltlen != 8))
54     return GPG_ERR_INV_VALUE;
55
56   secmode = _gcry_is_secure (passphrase) || _gcry_is_secure (keybuffer);
57
58   ec = _gcry_md_open (&md, hashalgo, secmode? GCRY_MD_FLAG_SECURE : 0);
59   if (ec)
60     return ec;
61
62   for (pass=0; used < keysize; pass++)
63     {
64       if (pass)
65         {
66           _gcry_md_reset (md);
67           for (i=0; i < pass; i++) /* Preset the hash context.  */
68             _gcry_md_putc (md, 0);
69         }
70
71       if (algo == GCRY_KDF_SALTED_S2K || algo == GCRY_KDF_ITERSALTED_S2K)
72         {
73           int len2 = passphraselen + 8;
74           unsigned long count = len2;
75
76           if (algo == GCRY_KDF_ITERSALTED_S2K)
77             {
78               count = iterations;
79               if (count < len2)
80                 count = len2;
81             }
82
83           while (count > len2)
84             {
85               _gcry_md_write (md, salt, saltlen);
86               _gcry_md_write (md, passphrase, passphraselen);
87               count -= len2;
88             }
89           if (count < saltlen)
90             _gcry_md_write (md, salt, count);
91           else
92             {
93               _gcry_md_write (md, salt, saltlen);
94               count -= saltlen;
95               _gcry_md_write (md, passphrase, count);
96             }
97         }
98       else
99         _gcry_md_write (md, passphrase, passphraselen);
100
101       _gcry_md_final (md);
102       i = _gcry_md_get_algo_dlen (hashalgo);
103       if (i > keysize - used)
104         i = keysize - used;
105       memcpy (key+used, _gcry_md_read (md, hashalgo), i);
106       used += i;
107     }
108   _gcry_md_close (md);
109   return 0;
110 }
111
112
113 /* Transform a passphrase into a suitable key of length KEYSIZE and
114    store this key in the caller provided buffer KEYBUFFER.  The caller
115    must provide PRFALGO which indicates the pseudorandom function to
116    use: This shall be the algorithms id of a hash algorithm; it is
117    used in HMAC mode.  SALT is a salt of length SALTLEN and ITERATIONS
118    gives the number of iterations.  */
119 gpg_err_code_t
120 _gcry_kdf_pkdf2 (const void *passphrase, size_t passphraselen,
121                  int hashalgo,
122                  const void *salt, size_t saltlen,
123                  unsigned long iterations,
124                  size_t keysize, void *keybuffer)
125 {
126   gpg_err_code_t ec;
127   gcry_md_hd_t md;
128   int secmode;
129   unsigned int dklen = keysize;
130   char *dk = keybuffer;
131   unsigned int hlen;   /* Output length of the digest function.  */
132   unsigned int l;      /* Rounded up number of blocks.  */
133   unsigned int r;      /* Number of octets in the last block.  */
134   char *sbuf;          /* Malloced buffer to concatenate salt and iter
135                           as well as space to hold TBUF and UBUF.  */
136   char *tbuf;          /* Buffer for T; ptr into SBUF, size is HLEN. */
137   char *ubuf;          /* Buffer for U; ptr into SBUF, size is HLEN. */
138   unsigned int lidx;   /* Current block number.  */
139   unsigned long iter;  /* Current iteration number.  */
140   unsigned int i;
141
142   /* NWe allow for a saltlen of 0 here to support scrypt.  It is not
143      clear whether rfc2898 allows for this this, thus we do a test on
144      saltlen > 0 only in gcry_kdf_derive.  */
145   if (!salt || !iterations || !dklen)
146     return GPG_ERR_INV_VALUE;
147
148   hlen = _gcry_md_get_algo_dlen (hashalgo);
149   if (!hlen)
150     return GPG_ERR_DIGEST_ALGO;
151
152   secmode = _gcry_is_secure (passphrase) || _gcry_is_secure (keybuffer);
153
154   /* We ignore step 1 from pksc5v2.1 which demands a check that dklen
155      is not larger that 0xffffffff * hlen.  */
156
157   /* Step 2 */
158   l = ((dklen - 1)/ hlen) + 1;
159   r = dklen - (l - 1) * hlen;
160
161   /* Setup buffers and prepare a hash context.  */
162   sbuf = (secmode
163           ? xtrymalloc_secure (saltlen + 4 + hlen + hlen)
164           : xtrymalloc (saltlen + 4 + hlen + hlen));
165   if (!sbuf)
166     return gpg_err_code_from_syserror ();
167   tbuf = sbuf + saltlen + 4;
168   ubuf = tbuf + hlen;
169
170   ec = _gcry_md_open (&md, hashalgo, (GCRY_MD_FLAG_HMAC
171                                       | (secmode?GCRY_MD_FLAG_SECURE:0)));
172   if (ec)
173     {
174       xfree (sbuf);
175       return ec;
176     }
177
178   ec = _gcry_md_setkey (md, passphrase, passphraselen);
179   if (ec)
180     {
181       _gcry_md_close (md);
182       xfree (sbuf);
183       return ec;
184     }
185
186   /* Step 3 and 4. */
187   memcpy (sbuf, salt, saltlen);
188   for (lidx = 1; lidx <= l; lidx++)
189     {
190       for (iter = 0; iter < iterations; iter++)
191         {
192           _gcry_md_reset (md);
193           if (!iter) /* Compute U_1:  */
194             {
195               sbuf[saltlen]     = (lidx >> 24);
196               sbuf[saltlen + 1] = (lidx >> 16);
197               sbuf[saltlen + 2] = (lidx >> 8);
198               sbuf[saltlen + 3] = lidx;
199               _gcry_md_write (md, sbuf, saltlen + 4);
200               memcpy (ubuf, _gcry_md_read (md, 0), hlen);
201               memcpy (tbuf, ubuf, hlen);
202             }
203           else /* Compute U_(2..c):  */
204             {
205               _gcry_md_write (md, ubuf, hlen);
206               memcpy (ubuf, _gcry_md_read (md, 0), hlen);
207               for (i=0; i < hlen; i++)
208                 tbuf[i] ^= ubuf[i];
209             }
210         }
211       if (lidx == l)  /* Last block.  */
212         memcpy (dk, tbuf, r);
213       else
214         {
215           memcpy (dk, tbuf, hlen);
216           dk += hlen;
217         }
218     }
219
220   _gcry_md_close (md);
221   xfree (sbuf);
222   return 0;
223 }
224
225
226 /* Derive a key from a passphrase.  KEYSIZE gives the requested size
227    of the keys in octets.  KEYBUFFER is a caller provided buffer
228    filled on success with the derived key.  The input passphrase is
229    taken from (PASSPHRASE,PASSPHRASELEN) which is an arbitrary memory
230    buffer.  ALGO specifies the KDF algorithm to use; these are the
231    constants GCRY_KDF_*.  SUBALGO specifies an algorithm used
232    internally by the KDF algorithms; this is usually a hash algorithm
233    but certain KDF algorithm may use it differently.  {SALT,SALTLEN}
234    is a salt as needed by most KDF algorithms.  ITERATIONS is a
235    positive integer parameter to most KDFs.  0 is returned on success,
236    or an error code on failure.  */
237 gpg_err_code_t
238 _gcry_kdf_derive (const void *passphrase, size_t passphraselen,
239                   int algo, int subalgo,
240                   const void *salt, size_t saltlen,
241                   unsigned long iterations,
242                   size_t keysize, void *keybuffer)
243 {
244   gpg_err_code_t ec;
245
246   if (!passphrase)
247     {
248       ec = GPG_ERR_INV_DATA;
249       goto leave;
250     }
251
252   if (!keybuffer || !keysize)
253     {
254       ec = GPG_ERR_INV_VALUE;
255       goto leave;
256     }
257
258
259   switch (algo)
260     {
261     case GCRY_KDF_SIMPLE_S2K:
262     case GCRY_KDF_SALTED_S2K:
263     case GCRY_KDF_ITERSALTED_S2K:
264       if (!passphraselen)
265         ec = GPG_ERR_INV_DATA;
266       else
267         ec = openpgp_s2k (passphrase, passphraselen, algo, subalgo,
268                           salt, saltlen, iterations, keysize, keybuffer);
269       break;
270
271     case GCRY_KDF_PBKDF1:
272       ec = GPG_ERR_UNSUPPORTED_ALGORITHM;
273       break;
274
275     case GCRY_KDF_PBKDF2:
276       if (!saltlen)
277         ec = GPG_ERR_INV_VALUE;
278       else
279         ec = _gcry_kdf_pkdf2 (passphrase, passphraselen, subalgo,
280                               salt, saltlen, iterations, keysize, keybuffer);
281       break;
282
283     case 41:
284     case GCRY_KDF_SCRYPT:
285 #if USE_SCRYPT
286       ec = _gcry_kdf_scrypt (passphrase, passphraselen, algo, subalgo,
287                              salt, saltlen, iterations, keysize, keybuffer);
288 #else
289       ec = GPG_ERR_UNSUPPORTED_ALGORITHM;
290 #endif /*USE_SCRYPT*/
291       break;
292
293     default:
294       ec = GPG_ERR_UNKNOWN_ALGORITHM;
295       break;
296     }
297
298  leave:
299   return ec;
300 }