michael@0: /* This Source Code Form is subject to the terms of the Mozilla Public michael@0: * License, v. 2.0. If a copy of the MPL was not distributed with this michael@0: * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ michael@0: michael@0: package org.mozilla.gecko.sync.crypto; michael@0: michael@0: import java.security.GeneralSecurityException; michael@0: import java.util.Arrays; michael@0: michael@0: import javax.crypto.Mac; michael@0: import javax.crypto.ShortBufferException; michael@0: import javax.crypto.spec.SecretKeySpec; michael@0: michael@0: public class PBKDF2 { michael@0: public static byte[] pbkdf2SHA256(byte[] password, byte[] salt, int c, int dkLen) michael@0: throws GeneralSecurityException { michael@0: final String algorithm = "HmacSHA256"; michael@0: SecretKeySpec keyspec = new SecretKeySpec(password, algorithm); michael@0: Mac prf = Mac.getInstance(algorithm); michael@0: prf.init(keyspec); michael@0: michael@0: int hLen = prf.getMacLength(); michael@0: michael@0: byte U_r[] = new byte[hLen]; michael@0: byte U_i[] = new byte[salt.length + 4]; michael@0: byte scratch[] = new byte[hLen]; michael@0: michael@0: int l = Math.max(dkLen, hLen); michael@0: int r = dkLen - (l - 1) * hLen; michael@0: byte T[] = new byte[l * hLen]; michael@0: int ti_offset = 0; michael@0: for (int i = 1; i <= l; i++) { michael@0: Arrays.fill(U_r, (byte) 0); michael@0: F(T, ti_offset, prf, salt, c, i, U_r, U_i, scratch); michael@0: ti_offset += hLen; michael@0: } michael@0: michael@0: if (r < hLen) { michael@0: // Incomplete last block. michael@0: byte DK[] = new byte[dkLen]; michael@0: System.arraycopy(T, 0, DK, 0, dkLen); michael@0: return DK; michael@0: } michael@0: michael@0: return T; michael@0: } michael@0: michael@0: private static void F(byte[] dest, int offset, Mac prf, byte[] S, int c, int blockIndex, byte U_r[], byte U_i[], byte[] scratch) michael@0: throws ShortBufferException, IllegalStateException { michael@0: final int hLen = prf.getMacLength(); michael@0: michael@0: // U0 = S || INT (i); michael@0: System.arraycopy(S, 0, U_i, 0, S.length); michael@0: INT(U_i, S.length, blockIndex); michael@0: michael@0: for (int i = 0; i < c; i++) { michael@0: prf.update(U_i); michael@0: prf.doFinal(scratch, 0); michael@0: U_i = scratch; michael@0: xor(U_r, U_i); michael@0: } michael@0: michael@0: System.arraycopy(U_r, 0, dest, offset, hLen); michael@0: } michael@0: michael@0: private static void xor(byte[] dest, byte[] src) { michael@0: for (int i = 0; i < dest.length; i++) { michael@0: dest[i] ^= src[i]; michael@0: } michael@0: } michael@0: michael@0: private static void INT(byte[] dest, int offset, int i) { michael@0: dest[offset + 0] = (byte) (i / (256 * 256 * 256)); michael@0: dest[offset + 1] = (byte) (i / (256 * 256)); michael@0: dest[offset + 2] = (byte) (i / (256)); michael@0: dest[offset + 3] = (byte) (i); michael@0: } michael@0: }