· 7 years ago · Jan 23, 2019, 01:04 PM
1public class Cryptogram {
2
3 private static byte[] iv;
4 private static IvParameterSpec ivspec;
5
6 public static byte[] Encrypt(String txt, SecretKey key) {
7 try {
8 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
9 cipher.init(Cipher.ENCRYPT_MODE, key);
10 byte[] cipherText = cipher.doFinal(txt.getBytes("UTF-8"));
11 iv = cipher.getIV();
12 ivspec = new IvParameterSpec(iv);
13 return cipherText;
14 } catch (Exception e) {
15 return e.toString().getBytes(Charset.forName("UTF-8"));
16 }
17 }
18
19 public static String Decrypt(byte[] txt, SecretKey key) {
20 try {
21 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", Security.getProvider("BC"));
22 cipher.init(Cipher.DECRYPT_MODE, key, ivspec);
23 String decryptString = new String(cipher.doFinal(txt), "UTF-8");
24 return decryptString;
25 } catch (Exception e) {
26 return e.toString();
27 }
28 }
29}