!7 import java.security.*; import java.security.spec.*; import javax.crypto.*; import javax.crypto.spec.*; p { S original = "hello"; byte[] data = original.getBytes("UTF-8"); printHex(data); Random ranGen = new SecureRandom(); byte[] salt = new byte[8]; // 8 grains of salt ranGen.nextBytes(salt); String pw = "pw"; byte[] enc = encrypt(data, pw, salt); printHex(enc); System.out.println("enc length: " + enc.length); byte[] dec = decrypt(enc, pw, salt); S decoded = fromUtf8(dec); System.out.println("decrypted: " + decoded); assertEquals(original, decoded); print("OK!!!!"); } static IvParameterSpec makeIV() { ret new IvParameterSpec(new byte[16]); } static SecretKey makeKey(S password, byte[] salt) throws Exception { /* Derive the key, given password and salt. */ SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1"); // only with unlimited strength: //KeySpec spec = new PBEKeySpec(password, salt, 65536, 256); // Let's try this: KeySpec spec = new PBEKeySpec(toCharArray(password), salt, 65536, 128); SecretKey tmp = factory.generateSecret(spec); SecretKey secret = new SecretKeySpec(tmp.getEncoded(), "AES"); return secret; } public static byte[] encrypt(byte[] data, S password, byte[] salt) { try { SecretKey secret = makeKey(password, salt); /* Encrypt the message. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); cipher.init(Cipher.ENCRYPT_MODE, secret, makeIV()); ByteArrayOutputStream baos = new ByteArrayOutputStream(); baos.write(cipher.update(data)); baos.write(cipher.doFinal()); byte[] ciphertext = baos.toByteArray(); return ciphertext; } catch (Exception e) { throw new RuntimeException(e); } } static byte[] decrypt(byte[] ciphertext, S password, byte[] salt) { try { SecretKey secret = makeKey(password, salt); /* Decrypt the message, given derived key and initialization vector. */ Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); cipher.init(Cipher.DECRYPT_MODE, secret, makeIV()); baos.write(cipher.update(ciphertext)); baos.write(cipher.doFinal()); return baos.toByteArray(); } catch (Exception e) { throw new RuntimeException(e); } }