authorgravatar for andrew@ziglang.orgAndrew Kelley <andrew@ziglang.org> 2020-09-17 17:31:58-04:00
committergravatar for noreply@github.comGitHub <noreply@github.com> 2020-09-17 17:31:58-04:00
logf125288c9be6e528906e34bacc51baae2586faf4
tree263d469e8b370b9eb13ffe4a46dcc8e9906928ab
parent5e3fa0e94f947c632aa584b9e13bfa2fe241fae1
parentc35703825f17bb2b1108a371bb0559b89ff2b2a0
signaturebadge-question-mark Signed by PGP key 4AEE18F83AFDEB23

Merge pull request #6336 from Rocknest/pbkdf2

Some changes to #6326 (pbkdf2)

2 files changed, 304 insertions(+), 0 deletions(-)

lib/std/crypto.zig+24
...@@ -35,6 +35,15 @@ pub const onetimeauth = struct {...@@ -35,6 +35,15 @@ pub const onetimeauth = struct {
35 pub const Poly1305 = @import("crypto/poly1305.zig").Poly1305;35 pub const Poly1305 = @import("crypto/poly1305.zig").Poly1305;
36};36};
3737
38/// A Key Derivation Function (KDF) is intended to turn a weak, human generated password into a
39/// strong key, suitable for cryptographic uses. It does this by salting and stretching the
40/// password. Salting injects non-secret random data, so that identical passwords will be converted
41/// into unique keys. Stretching applies a deliberately slow hashing function to frustrate
42/// brute-force guessing.
43pub const kdf = struct {
44 pub const pbkdf2 = @import("crypto/pbkdf2.zig").pbkdf2;
45};
46
38/// Core functions, that should rarely be used directly by applications.47/// Core functions, that should rarely be used directly by applications.
39pub const core = struct {48pub const core = struct {
40 pub const aes = @import("crypto/aes.zig");49 pub const aes = @import("crypto/aes.zig");
...@@ -70,6 +79,20 @@ const std = @import("std.zig");...@@ -70,6 +79,20 @@ const std = @import("std.zig");
70pub const randomBytes = std.os.getrandom;79pub const randomBytes = std.os.getrandom;
7180
72test "crypto" {81test "crypto" {
82 inline for (std.meta.declarations(@This())) |decl| {
83 switch (decl.data) {
84 .Type => |t| {
85 std.meta.refAllDecls(t);
86 },
87 .Var => |v| {
88 _ = v;
89 },
90 .Fn => |f| {
91 _ = f;
92 },
93 }
94 }
95
73 _ = @import("crypto/aes.zig");96 _ = @import("crypto/aes.zig");
74 _ = @import("crypto/blake2.zig");97 _ = @import("crypto/blake2.zig");
75 _ = @import("crypto/blake3.zig");98 _ = @import("crypto/blake3.zig");
...@@ -77,6 +100,7 @@ test "crypto" {...@@ -77,6 +100,7 @@ test "crypto" {
77 _ = @import("crypto/gimli.zig");100 _ = @import("crypto/gimli.zig");
78 _ = @import("crypto/hmac.zig");101 _ = @import("crypto/hmac.zig");
79 _ = @import("crypto/md5.zig");102 _ = @import("crypto/md5.zig");
103 _ = @import("crypto/pbkdf2.zig");
80 _ = @import("crypto/poly1305.zig");104 _ = @import("crypto/poly1305.zig");
81 _ = @import("crypto/sha1.zig");105 _ = @import("crypto/sha1.zig");
82 _ = @import("crypto/sha2.zig");106 _ = @import("crypto/sha2.zig");
lib/std/crypto/pbkdf2.zig created+280
...@@ -0,0 +1,280 @@
1// SPDX-License-Identifier: MIT
2// Copyright (c) 2015-2020 Zig Contributors
3// This file is part of [zig](https://ziglang.org/), which is MIT licensed.
4// The MIT license requires this copyright notice to be included in all copies
5// and substantial portions of the software.
6
7const std = @import("std");
8const mem = std.mem;
9const maxInt = std.math.maxInt;
10
11// RFC 2898 Section 5.2
12//
13// FromSpec:
14//
15// PBKDF2 applies a pseudorandom function (see Appendix B.1 for an
16// example) to derive keys. The length of the derived key is essentially
17// unbounded. (However, the maximum effective search space for the
18// derived key may be limited by the structure of the underlying
19// pseudorandom function. See Appendix B.1 for further discussion.)
20// PBKDF2 is recommended for new applications.
21//
22// PBKDF2 (P, S, c, dkLen)
23//
24// Options: PRF underlying pseudorandom function (hLen
25// denotes the length in octets of the
26// pseudorandom function output)
27//
28// Input: P password, an octet string
29// S salt, an octet string
30// c iteration count, a positive integer
31// dkLen intended length in octets of the derived
32// key, a positive integer, at most
33// (2^32 - 1) * hLen
34//
35// Output: DK derived key, a dkLen-octet string
36
37// Based on Apple's CommonKeyDerivation, based originally on code by Damien Bergamini.
38
39pub const Pbkdf2Error = error{
40 /// At least one round is required
41 TooFewRounds,
42
43 /// Maximum length of the derived key is `maxInt(u32) * Prf.mac_length`
44 DerivedKeyTooLong,
45};
46
47/// Apply PBKDF2 to generate a key from a password.
48///
49/// PBKDF2 is defined in RFC 2898, and is a recommendation of NIST SP 800-132.
50///
51/// derivedKey: Slice of appropriate size for generated key. Generally 16 or 32 bytes in length.
52/// May be uninitialized. All bytes will be overwritten.
53/// Maximum size is `maxInt(u32) * Hash.digest_length`
54/// It is a programming error to pass buffer longer than the maximum size.
55///
56/// password: Arbitrary sequence of bytes of any length, including empty.
57///
58/// salt: Arbitrary sequence of bytes of any length, including empty. A common length is 8 bytes.
59///
60/// rounds: Iteration count. Must be greater than 0. Common values range from 1,000 to 100,000.
61/// Larger iteration counts improve security by increasing the time required to compute
62/// the derivedKey. It is common to tune this parameter to achieve approximately 100ms.
63///
64/// Prf: Pseudo-random function to use. A common choice is `std.crypto.auth.hmac.HmacSha256`.
65pub fn pbkdf2(derivedKey: []u8, password: []const u8, salt: []const u8, rounds: u32, comptime Prf: type) Pbkdf2Error!void {
66 if (rounds < 1) return error.TooFewRounds;
67
68 const dkLen = derivedKey.len;
69 const hLen = Prf.mac_length;
70 comptime std.debug.assert(hLen >= 1);
71
72 // FromSpec:
73 //
74 // 1. If dkLen > maxInt(u32) * hLen, output "derived key too long" and
75 // stop.
76 //
77 if (comptime (maxInt(usize) > maxInt(u32) * hLen) and (dkLen > @as(usize, maxInt(u32) * hLen))) {
78 // If maxInt(usize) is less than `maxInt(u32) * hLen` then dkLen is always inbounds
79 return error.DerivedKeyTooLong;
80 }
81
82 // FromSpec:
83 //
84 // 2. Let l be the number of hLen-long blocks of bytes in the derived key,
85 // rounding up, and let r be the number of bytes in the last
86 // block
87 //
88
89 // l will not overflow, proof:
90 // let `L(dkLen, hLen) = (dkLen + hLen - 1) / hLen`
91 // then `L^-1(l, hLen) = l*hLen - hLen + 1`
92 // 1) L^-1(maxInt(u32), hLen) <= maxInt(u32)*hLen
93 // 2) maxInt(u32)*hLen - hLen + 1 <= maxInt(u32)*hLen // subtract maxInt(u32)*hLen + 1
94 // 3) -hLen <= -1 // multiply by -1
95 // 4) hLen >= 1
96 const r_ = dkLen % hLen;
97 const l = @intCast(u32, (dkLen / hLen) + @as(u1, if (r_ == 0) 0 else 1)); // original: (dkLen + hLen - 1) / hLen
98 const r = if (r_ == 0) hLen else r_;
99
100 // FromSpec:
101 //
102 // 3. For each block of the derived key apply the function F defined
103 // below to the password P, the salt S, the iteration count c, and
104 // the block index to compute the block:
105 //
106 // T_1 = F (P, S, c, 1) ,
107 // T_2 = F (P, S, c, 2) ,
108 // ...
109 // T_l = F (P, S, c, l) ,
110 //
111 // where the function F is defined as the exclusive-or sum of the
112 // first c iterates of the underlying pseudorandom function PRF
113 // applied to the password P and the concatenation of the salt S
114 // and the block index i:
115 //
116 // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
117 //
118 // where
119 //
120 // U_1 = PRF (P, S || INT (i)) ,
121 // U_2 = PRF (P, U_1) ,
122 // ...
123 // U_c = PRF (P, U_{c-1}) .
124 //
125 // Here, INT (i) is a four-octet encoding of the integer i, most
126 // significant octet first.
127 //
128 // 4. Concatenate the blocks and extract the first dkLen octets to
129 // produce a derived key DK:
130 //
131 // DK = T_1 || T_2 || ... || T_l<0..r-1>
132 var block: u32 = 0; // Spec limits to u32
133 while (block < l) : (block += 1) {
134 var prevBlock: [hLen]u8 = undefined;
135 var newBlock: [hLen]u8 = undefined;
136
137 // U_1 = PRF (P, S || INT (i))
138 const blockIndex = mem.toBytes(mem.nativeToBig(u32, block + 1)); // Block index starts at 0001
139 var ctx = Prf.init(password);
140 ctx.update(salt);
141 ctx.update(blockIndex[0..]);
142 ctx.final(prevBlock[0..]);
143
144 // Choose portion of DK to write into (T_n) and initialize
145 const offset = block * hLen;
146 const blockLen = if (block != l - 1) hLen else r;
147 const dkBlock: []u8 = derivedKey[offset..][0..blockLen];
148 mem.copy(u8, dkBlock, prevBlock[0..dkBlock.len]);
149
150 var i: u32 = 1;
151 while (i < rounds) : (i += 1) {
152 // U_c = PRF (P, U_{c-1})
153 Prf.create(&newBlock, prevBlock[0..], password);
154 mem.copy(u8, prevBlock[0..], newBlock[0..]);
155
156 // F (P, S, c, i) = U_1 \xor U_2 \xor ... \xor U_c
157 for (dkBlock) |_, j| {
158 dkBlock[j] ^= newBlock[j];
159 }
160 }
161 }
162}
163
164const htest = @import("test.zig");
165const HmacSha1 = std.crypto.auth.hmac.HmacSha1;
166
167// RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors
168test "RFC 6070 one iteration" {
169 const p = "password";
170 const s = "salt";
171 const c = 1;
172 const dkLen = 20;
173
174 var derivedKey: [dkLen]u8 = undefined;
175
176 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
177
178 const expected = "0c60c80f961f0e71f3a9b524af6012062fe037a6";
179
180 htest.assertEqual(expected, derivedKey[0..]);
181}
182
183test "RFC 6070 two iterations" {
184 const p = "password";
185 const s = "salt";
186 const c = 2;
187 const dkLen = 20;
188
189 var derivedKey: [dkLen]u8 = undefined;
190
191 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
192
193 const expected = "ea6c014dc72d6f8ccd1ed92ace1d41f0d8de8957";
194
195 htest.assertEqual(expected, derivedKey[0..]);
196}
197
198test "RFC 6070 4096 iterations" {
199 const p = "password";
200 const s = "salt";
201 const c = 4096;
202 const dkLen = 20;
203
204 var derivedKey: [dkLen]u8 = undefined;
205
206 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
207
208 const expected = "4b007901b765489abead49d926f721d065a429c1";
209
210 htest.assertEqual(expected, derivedKey[0..]);
211}
212
213test "RFC 6070 16,777,216 iterations" {
214 // These iteration tests are slow so we always skip them. Results have been verified.
215 if (true) {
216 return error.SkipZigTest;
217 }
218
219 const p = "password";
220 const s = "salt";
221 const c = 16777216;
222 const dkLen = 20;
223
224 var derivedKey = [_]u8{0} ** dkLen;
225
226 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
227
228 const expected = "eefe3d61cd4da4e4e9945b3d6ba2158c2634e984";
229
230 htest.assertEqual(expected, derivedKey[0..]);
231}
232
233test "RFC 6070 multi-block salt and password" {
234 const p = "passwordPASSWORDpassword";
235 const s = "saltSALTsaltSALTsaltSALTsaltSALTsalt";
236 const c = 4096;
237 const dkLen = 25;
238
239 var derivedKey: [dkLen]u8 = undefined;
240
241 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
242
243 const expected = "3d2eec4fe41c849b80c8d83662c0e44a8b291a964cf2f07038";
244
245 htest.assertEqual(expected, derivedKey[0..]);
246}
247
248test "RFC 6070 embedded NUL" {
249 const p = "pass\x00word";
250 const s = "sa\x00lt";
251 const c = 4096;
252 const dkLen = 16;
253
254 var derivedKey: [dkLen]u8 = undefined;
255
256 try pbkdf2(&derivedKey, p, s, c, HmacSha1);
257
258 const expected = "56fa6aa75548099dcc37d7f03425e0c3";
259
260 htest.assertEqual(expected, derivedKey[0..]);
261}
262
263test "Very large dkLen" {
264 // This test allocates 8GB of memory and is expected to take several hours to run.
265 if (true) {
266 return error.SkipZigTest;
267 }
268 const p = "password";
269 const s = "salt";
270 const c = 1;
271 const dkLen = 1 << 33;
272
273 var derivedKey = try std.testing.allocator.alloc(u8, dkLen);
274 defer {
275 std.testing.allocator.free(derivedKey);
276 }
277
278 try pbkdf2(derivedKey, p, s, c, HmacSha1);
279 // Just verify this doesn't crash with an overflow
280}