/* Password based encryption and decryption with AES. It is taken from * *https://stackoverflow.com/questions/43190139/how-to-decrypt-a-string-using-pbe-algorithm * * with a few insignificant changes */ import java.security.InvalidAlgorithmParameterException; import java.security.InvalidKeyException; import java.security.NoSuchAlgorithmException; import java.security.spec.InvalidKeySpecException; import java.security.spec.InvalidParameterSpecException; import java.security.spec.KeySpec; import javax.crypto.*; import javax.crypto.spec.*; import java.security.Key; import java.security.SecureRandom; import javax.crypto.Cipher; import javax.crypto.SecretKeyFactory; import javax.crypto.spec.IvParameterSpec; import javax.crypto.spec.PBEKeySpec; import javax.crypto.spec.SecretKeySpec; import javax.crypto.spec.PBEParameterSpec; import javax.crypto.spec.SecretKeySpec; public class PBE2 { public static void main( String[] args) throws Exception { SecureRandom rnd = new SecureRandom(); byte[] iv = new byte[16]; rnd.nextBytes(iv); byte[] salt = { (byte)0xc7, (byte)0x73, (byte)0x21, (byte)0x8c, (byte)0x7e, (byte)0xc8, (byte)0xee, (byte)0x99 }; String password = "password"; byte[] plaintext = "plaintext".getBytes(); IvParameterSpec ivParamSpec = new IvParameterSpec(iv); PBEParameterSpec pbeParamSpec = new PBEParameterSpec(salt, 10000, ivParamSpec); PBEKeySpec keySpec = new PBEKeySpec(password.toCharArray()); try { SecretKeyFactory kf = SecretKeyFactory.getInstance("PBEWithHmacSHA256AndAES_128"); SecretKey secretKey = kf.generateSecret(keySpec); System.out.println(new String(secretKey.getEncoded())); // Encrypt Cipher enc = Cipher.getInstance("PBEWithHmacSHA256AndAES_128"); enc.init(Cipher.ENCRYPT_MODE, secretKey, pbeParamSpec); byte[] ciphertext = enc.doFinal(plaintext); System.out.println("Encrypted text: " + Utils.toHex(ciphertext)); // Decrypt Cipher dec = Cipher.getInstance("PBEWithHmacSHA256AndAES_128"); dec.init(Cipher.DECRYPT_MODE, secretKey, pbeParamSpec); byte[] decrypted = dec.doFinal(ciphertext); String message = new String(decrypted); System.out.println(message); } catch (NoSuchAlgorithmException | InvalidKeySpecException e) { e.printStackTrace(); } } }