| 22 | |
| 23 | /* Encryption Method */ |
| 24 | public static String encrypt(String strToEncrypt) |
| 25 | { |
| 26 | try |
| 27 | { |
| 28 | /* Declare a byte array. */ |
| 29 | byte[] iv = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0}; |
| 30 | IvParameterSpec ivspec = new IvParameterSpec(iv); |
| 31 | /* Create factory for secret keys. */ |
| 32 | SecretKeyFactory factory = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256"); |
| 33 | /* PBEKeySpec class implements KeySpec interface. */ |
| 34 | KeySpec spec = new PBEKeySpec(SECRET_KEY.toCharArray(), SALTVALUE.getBytes(), 65536, 256); |
| 35 | SecretKey tmp = factory.generateSecret(spec); |
| 36 | SecretKeySpec secretKey = new SecretKeySpec(tmp.getEncoded(), "AES"); |
| 37 | Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding"); |
| 38 | cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivspec); |
| 39 | /* Retruns encrypted value. */ |
| 40 | return Base64.getEncoder() |
| 41 | .encodeToString(cipher.doFinal(strToEncrypt.getBytes(StandardCharsets.UTF_8))); |
| 42 | } |
| 43 | catch (InvalidAlgorithmParameterException | InvalidKeyException | NoSuchAlgorithmException | InvalidKeySpecException | BadPaddingException | IllegalBlockSizeException | NoSuchPaddingException e) |
| 44 | { |
| 45 | System.out.println("Error occured during encryption: " + e.toString()); |
| 46 | } |
| 47 | return null; |
| 48 | } |
| 49 | |
| 50 | /* Decryption Method */ |
| 51 | public static String decrypt(String strToDecrypt) |