1 /* gc-pbkdf2-sha1.c --- Password-Based Key Derivation Function a'la PKCS#5
2 Copyright (C) 2002, 2003, 2004, 2005, 2006, 2009 Free Software Foundation, Inc.
4 This program is free software; you can redistribute it and/or modify
5 it under the terms of the GNU General Public License as published by
6 the Free Software Foundation; either version 2, or (at your option)
9 This program is distributed in the hope that it will be useful,
10 but WITHOUT ANY WARRANTY; without even the implied warranty of
11 MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
12 GNU General Public License for more details.
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software Foundation,
16 Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */
18 /* Written by Simon Josefsson. */
19 /* Imported from gnulib. */
21 #include <grub/crypto.h>
23 #include <grub/misc.h>
26 GRUB_MOD_LICENSE ("GPLv2+");
28 /* Implement PKCS#5 PBKDF2 as per RFC 2898. The PRF to use is HMAC variant
29 of digest supplied by MD. Inputs are the password P of length PLEN,
30 the salt S of length SLEN, the iteration counter C (> 0), and the
31 desired derived output length DKLEN. Output buffer is DK which
32 must have room for at least DKLEN octets. The output buffer will
33 be filled with the derived data. */
36 grub_crypto_pbkdf2 (const struct gcry_md_spec
*md
,
37 const grub_uint8_t
*P
, grub_size_t Plen
,
38 const grub_uint8_t
*S
, grub_size_t Slen
,
40 grub_uint8_t
*DK
, grub_size_t dkLen
)
42 unsigned int hLen
= md
->mdlen
;
43 grub_uint8_t U
[GRUB_CRYPTO_MAX_MDLEN
];
44 grub_uint8_t T
[GRUB_CRYPTO_MAX_MDLEN
];
52 grub_size_t tmplen
= Slen
+ 4;
54 if (md
->mdlen
> GRUB_CRYPTO_MAX_MDLEN
|| md
->mdlen
== 0)
55 return GPG_ERR_INV_ARG
;
58 return GPG_ERR_INV_ARG
;
61 return GPG_ERR_INV_ARG
;
63 if (dkLen
> 4294967295U)
64 return GPG_ERR_INV_ARG
;
66 l
= ((dkLen
- 1) / hLen
) + 1;
67 r
= dkLen
- (l
- 1) * hLen
;
69 tmp
= grub_malloc (tmplen
);
71 return GPG_ERR_OUT_OF_MEMORY
;
73 grub_memcpy (tmp
, S
, Slen
);
75 for (i
= 1; i
- 1 < l
; i
++)
77 grub_memset (T
, 0, hLen
);
79 for (u
= 0; u
< c
; u
++)
83 tmp
[Slen
+ 0] = (i
& 0xff000000) >> 24;
84 tmp
[Slen
+ 1] = (i
& 0x00ff0000) >> 16;
85 tmp
[Slen
+ 2] = (i
& 0x0000ff00) >> 8;
86 tmp
[Slen
+ 3] = (i
& 0x000000ff) >> 0;
88 rc
= grub_crypto_hmac_buffer (md
, P
, Plen
, tmp
, tmplen
, U
);
91 rc
= grub_crypto_hmac_buffer (md
, P
, Plen
, U
, hLen
, U
);
93 if (rc
!= GPG_ERR_NO_ERROR
)
99 for (k
= 0; k
< hLen
; k
++)
103 grub_memcpy (DK
+ (i
- 1) * hLen
, T
, i
== l
? r
: hLen
);
108 return GPG_ERR_NO_ERROR
;