|
1 /* This Source Code Form is subject to the terms of the Mozilla Public |
|
2 * License, v. 2.0. If a copy of the MPL was not distributed with this |
|
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ |
|
4 |
|
5 package org.mozilla.gecko.sync.crypto; |
|
6 |
|
7 import java.security.GeneralSecurityException; |
|
8 import java.util.Arrays; |
|
9 |
|
10 import javax.crypto.Mac; |
|
11 import javax.crypto.ShortBufferException; |
|
12 import javax.crypto.spec.SecretKeySpec; |
|
13 |
|
14 public class PBKDF2 { |
|
15 public static byte[] pbkdf2SHA256(byte[] password, byte[] salt, int c, int dkLen) |
|
16 throws GeneralSecurityException { |
|
17 final String algorithm = "HmacSHA256"; |
|
18 SecretKeySpec keyspec = new SecretKeySpec(password, algorithm); |
|
19 Mac prf = Mac.getInstance(algorithm); |
|
20 prf.init(keyspec); |
|
21 |
|
22 int hLen = prf.getMacLength(); |
|
23 |
|
24 byte U_r[] = new byte[hLen]; |
|
25 byte U_i[] = new byte[salt.length + 4]; |
|
26 byte scratch[] = new byte[hLen]; |
|
27 |
|
28 int l = Math.max(dkLen, hLen); |
|
29 int r = dkLen - (l - 1) * hLen; |
|
30 byte T[] = new byte[l * hLen]; |
|
31 int ti_offset = 0; |
|
32 for (int i = 1; i <= l; i++) { |
|
33 Arrays.fill(U_r, (byte) 0); |
|
34 F(T, ti_offset, prf, salt, c, i, U_r, U_i, scratch); |
|
35 ti_offset += hLen; |
|
36 } |
|
37 |
|
38 if (r < hLen) { |
|
39 // Incomplete last block. |
|
40 byte DK[] = new byte[dkLen]; |
|
41 System.arraycopy(T, 0, DK, 0, dkLen); |
|
42 return DK; |
|
43 } |
|
44 |
|
45 return T; |
|
46 } |
|
47 |
|
48 private static void F(byte[] dest, int offset, Mac prf, byte[] S, int c, int blockIndex, byte U_r[], byte U_i[], byte[] scratch) |
|
49 throws ShortBufferException, IllegalStateException { |
|
50 final int hLen = prf.getMacLength(); |
|
51 |
|
52 // U0 = S || INT (i); |
|
53 System.arraycopy(S, 0, U_i, 0, S.length); |
|
54 INT(U_i, S.length, blockIndex); |
|
55 |
|
56 for (int i = 0; i < c; i++) { |
|
57 prf.update(U_i); |
|
58 prf.doFinal(scratch, 0); |
|
59 U_i = scratch; |
|
60 xor(U_r, U_i); |
|
61 } |
|
62 |
|
63 System.arraycopy(U_r, 0, dest, offset, hLen); |
|
64 } |
|
65 |
|
66 private static void xor(byte[] dest, byte[] src) { |
|
67 for (int i = 0; i < dest.length; i++) { |
|
68 dest[i] ^= src[i]; |
|
69 } |
|
70 } |
|
71 |
|
72 private static void INT(byte[] dest, int offset, int i) { |
|
73 dest[offset + 0] = (byte) (i / (256 * 256 * 256)); |
|
74 dest[offset + 1] = (byte) (i / (256 * 256)); |
|
75 dest[offset + 2] = (byte) (i / (256)); |
|
76 dest[offset + 3] = (byte) (i); |
|
77 } |
|
78 } |