· 7 years ago · Apr 30, 2018, 05:20 PM
1public static String encrypt(String plainText, String password) throws
2 NoSuchAlgorithmException,
3 InvalidKeySpecException,
4 NoSuchPaddingException,
5 InvalidParameterSpecException,
6 IllegalBlockSizeException,
7 BadPaddingException,
8 UnsupportedEncodingException,
9 InvalidKeyException,
10 InvalidAlgorithmParameterException
11{
12 byte[] saltBytes = salt.getBytes("UTF-8");
13 byte[] ivBytes = initializationVector.getBytes("UTF-8");
14 SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
15
16 PBEKeySpec spec = new PBEKeySpec(
17 password.toCharArray(),
18 saltBytes,
19 pswdIterations,
20 keySize
21 );
22 SecretKey secretKey = factory.generateSecret(spec);
23 SecretKeySpec secret = new SecretKeySpec(secretKey.getEncoded(), "AES");
24 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
25 cipher.init(Cipher.ENCRYPT_MODE, secret, new IvParameterSpec(ivBytes));
26 byte[] encryptedTextBytes = cipher.doFinal(plainText.getBytes("UTF-8"));
27 return Base64.encodeToString(encryptedTextBytes, 0);
28}