PBKDF2PasswordEncryptor implements PasswordEncryptor { @Override public String encrypt(String saltSeed, String password) throws IllegalStateException { if (saltSeed == null || password == null) { throw new IllegalArgumentException("saltSeed and password must not be null."); } if (saltSeed.isEmpty() || password.isEmpty()) { return ""; } KeySpec spec = new PBEKeySpec(password.toCharArray(), getSalt(saltSeed), getIterationCount(), getKeyLength()); byte[] encryptPassword; try { do { encryptPassword = FACTORY.get().generateSecret(spec).getEncoded(); } while (!isSuccessEncryption(encryptPassword)); } catch (InvalidKeySpecException e) { throw new RuntimeException(e); } return Base64Util.encode(encryptPassword); }  @Override String encrypt(String saltSeed, String password); int getIterationCount(); void setIterationCount(int iterationCount); int getKeyLength(); void setKeyLength(int keyLength); String getFixedSalt(); void setFixedSalt(String fixedSalt);  }
@Test public void testEncrypt() { assertThat("同じパスワードを暗号化すると、同じ文字列となること。", sut.encrypt("salt", "password"), is(sut.encrypt("salt", "password"))); assertThat("異なるパスワードを暗号化すると、異なる文字列となること。", sut.encrypt("salt", "one"), is(not(sut.encrypt("salt", "another")))); assertThat("同じパスワードでも、ソルトが異なると、異なる文字列となること。", sut.encrypt("one", "password"), is(not(sut.encrypt("another", "password")))); PBKDF2PasswordEncryptor itr = createEncryptor(); itr.setIterationCount(1); assertThat("設定したiterationCountでストレッチングされること。", itr.encrypt("salt", "password"), is(not(sut.encrypt("salt", "password")))); PBKDF2PasswordEncryptor len = createEncryptor(); len.setKeyLength(160); assertThat("設定したkeyLengthの長さの暗号化されたパスワードが生成されること", len.encrypt("salt", "password").length(), is(28)); PBKDF2PasswordEncryptor fix = createEncryptor(); fix.setFixedSalt("someOtherFixedSaltString"); assertThat("設定したfixedSaltを使用してソルトが生成されていること。", fix.encrypt("salt", "password"), is(not(sut.encrypt("salt", "password")))); }
@Test(expected = IllegalStateException.class) public void testEncrypt_NoFixedSalt() { new PBKDF2PasswordEncryptor().encrypt("salt", "password"); }
@Test(expected = IllegalArgumentException.class) public void testEncrypt_NullSaltSeed() { sut.encrypt(null, "password"); }
@Test(expected = IllegalArgumentException.class) public void testEncrypt_NullPassword() { sut.encrypt("saltSeed", null); }