PasswordUtils { private String encrypt() throws IOException { String ret = null; String strToEncrypt = null; if (password == null) { strToEncrypt = ""; } else { strToEncrypt = password.length() + LEN_SEPARATOR_STR + password; } try { Cipher engine = Cipher.getInstance(cryptAlgo); PBEKeySpec keySpec = new PBEKeySpec(encryptKey); SecretKeyFactory skf = SecretKeyFactory.getInstance(cryptAlgo); SecretKey key = skf.generateSecret(keySpec); engine.init(Cipher.ENCRYPT_MODE, key, new PBEParameterSpec(salt, iterationCount, new IvParameterSpec(iv))); byte[] encryptedStr = engine.doFinal(strToEncrypt.getBytes()); ret = new String(Base64.encode(encryptedStr)); } catch(Throwable t) { LOG.error("Unable to encrypt password due to error", t); throw new IOException("Unable to encrypt password due to error", t); } return ret; } PasswordUtils(String aPassword); static String encryptPassword(String aPassword); static PasswordUtils build(String aPassword); static String decryptPassword(String aPassword); static boolean needsIv(String cryptoAlgo); static String generateIvIfNeeded(String cryptAlgo); String getCryptAlgo(); String getPassword(); int getIterationCount(); char[] getEncryptKey(); byte[] getSalt(); byte[] getIv(); String getIvAsString(); static String getDecryptPassword(String password); static final String PBE_SHA512_AES_128; static final String DEFAULT_CRYPT_ALGO; static final String DEFAULT_ENCRYPT_KEY; static final String DEFAULT_SALT; static final int DEFAULT_ITERATION_COUNT; static final byte[] DEFAULT_INITIAL_VECTOR; }
@Test public void testEncrypt() throws IOException { String encryptedPassword = PasswordUtils.encryptPassword("secretPasswordNoOneWillEverKnow"); assertNotNull(encryptedPassword); assertEquals("ljoJ3gf4T018Xr+BujPAqBDW8Onp1PqprsLKmxus8pGGBETtAVU6OQ==", encryptedPassword); }