· 6 years ago · Feb 20, 2019, 05:30 PM
1public static String encryptWithAES_GCM(String plainText, String keyHex, String ivHex) {
2 byte[] cipherText;
3 byte[] key = Hex.decode(keyHex);
4 byte[] iv = Hex.decode(ivHex);
5
6 try {
7 SecretKeySpec secretKey = new SecretKeySpec(key, "AES");
8 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding", "BC");
9 GCMParameterSpec parameterSpec = new GCMParameterSpec(128, iv);
10 cipher.init(Cipher.ENCRYPT_MODE, secretKey, parameterSpec);
11 cipherText = cipher.doFinal(plainText.getBytes());
12 } catch (Exception e) {
13 throw new RuntimeException(e);
14 }
15
16 return Base64.toBase64String(cipherText);
17}