| ... | @@ -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 | |
| 7 | const std = @import("std"); |
| 8 | const mem = std.mem; |
| 9 | const 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 | |
| 39 | pub 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`. |
| 65 | pub 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 | |
| 164 | const htest = @import("test.zig"); |
| 165 | const HmacSha1 = std.crypto.auth.hmac.HmacSha1; |
| 166 | |
| 167 | // RFC 6070 PBKDF2 HMAC-SHA1 Test Vectors |
| 168 | test "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 | |
| 183 | test "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 | |
| 198 | test "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 | |
| 213 | test "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 | |
| 233 | test "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 | |
| 248 | test "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 | |
| 263 | test "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 | } |