BcPKCS5S2KeyDerivationFunctionFactory extends AbstractBcKDFFactory { @Override public KeyDerivationFunction getInstance(KeyDerivationFunctionParameters params) { if (!(params instanceof PBKDF2Parameters)) { throw new IllegalArgumentException("Invalid parameter used for PKCS5S2 function: " + params.getClass().getName()); } PBKDF2Parameters kdfParams = (PBKDF2Parameters) params; PKCS5S2ParametersGenerator generator; BcDigestFactory factory = null; if (kdfParams.getPseudoRandomFuntionHint() != null) { factory = this.getDigestFactory(kdfParams.getPseudoRandomFuntionHint()); generator = new PKCS5S2ParametersGenerator(factory.getDigestInstance()); } else { generator = new PKCS5S2ParametersGenerator(); } return new AbstractBcPBKDF2(generator, (PBKDF2Parameters) params, (factory != null) ? toHmacAlgId(factory.getAlgorithmIdentifier()) : HMAC_SHA1) { @Override public KeyDerivationFunc getKeyDerivationFunction() { PBKDF2Parameters parameters = (PBKDF2Parameters) getParameters(); AlgorithmIdentifier algId = getPRFAlgorithmIdentifier(); return new KeyDerivationFunc(PKCSObjectIdentifiers.id_PBKDF2, (isKeySizeOverwritten()) ? new PBKDF2Params(parameters.getSalt(), parameters.getIterationCount(), algId) : new PBKDF2Params(parameters.getSalt(), parameters.getIterationCount(), parameters.getKeySize(), algId)); } }; }  @Override KeyDerivationFunction getInstance(KeyDerivationFunctionParameters params); @Override KeyDerivationFunction getInstance(ASN1Encodable parameters);  }
@Test public void pbkdf2SerializationDeserializationTest() throws Exception { byte[] password = PasswordToByteConverter.convert("password"); KeyDerivationFunction kdf = getKDFInstance(new PBKDF2Parameters(32, 1000)); KeyWithIVParameters params = kdf.derive(password, 8); KeyDerivationFunction kdf2 = factory.getInstance(kdf.getEncoded()); KeyWithIVParameters params2 = kdf2.derive(password, 8); assertThat(params.getKey(), equalTo(params2.getKey())); assertThat(params2.getIV(), equalTo(params2.getIV())); }