· 5 years ago · Nov 15, 2019, 03:46 PM
1public static void encrypt(String password, String secret) throws NoSuchAlgorithmException, InvalidKeySpecException, IllegalBlockSizeException, BadPaddingException, InvalidKeyException, InvalidAlgorithmParameterException, NoSuchPaddingException, IOException {
2 byte[] salt = getSalt();
3 byte[] iv = getIV();
4 PBEKeySpec spec = new PBEKeySpec(secret.toCharArray(), salt, 100000, 256);
5 SecretKeyFactory skf = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
6 byte[] keyBytes = skf.generateSecret(spec).getEncoded();
7 SecretKey key = new SecretKeySpec(keyBytes, "AES");
8 IvParameterSpec ivspec = new IvParameterSpec(iv);
9 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
10 cipher.init(Cipher.ENCRYPT_MODE, key, ivspec);
11 byte[] encrypted = cipher.doFinal(password.getBytes());