· 6 years ago · Mar 21, 2019, 12:40 PM
1public String encrypt(String plainText, String authenticationTag) throws GeneralSecurityException, IOException {
2 Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
3 final int blockSize = cipher.getBlockSize();
4 SecretKey secretKey = readKeyFile(...);
5 byte[] plainTextByte = plainText.trim().getBytes(Charset.forName("UTF-8"));
6 byte[] ivBytes = generateIV();
7 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(GCM_TAG_LENGTH, ivBytes));
8 cipher.updateAAD(authenticationTag.getBytes(Charset.forName("UTF-8")));
9 byte[] encryptedMessage = cipher.doFinal(plainTextByte);
10 byte iv_and_encryptedMessage[] = concatIvAndCipher(ivBytes, encryptedMessage, blockSize);
11 Base64.Encoder encoder = Base64.getEncoder().withoutPadding();
12 String iv_and_encryptedText = encoder.encodeToString(iv_and_encryptedMessage);
13 return iv_and_encryptedText;
14 }
15
16 public String decrypt(String iv_and_encryptedTextBase64, String authenticationTag)
17 throws GeneralSecurityException, IOException {
18 Cipher cipher = Cipher.getInstance(ALGORITHM_MODE_PADDING);
19 final int blockSize = cipher.getBlockSize();
20 Base64.Decoder decoder = Base64.getDecoder();
21 byte[] iv_and_encryptedMessage = decoder.decode(iv_and_encryptedTextBase64.trim());
22 byte[] ivBytes = extractIvFrom(iv_and_encryptedMessage, blockSize);
23 byte[] encryptedTextBytes = extractEncryptedMessageFrom(iv_and_encryptedMessage, blockSize);
24 SecretKey secretKey = readKeyFile(...);
25 cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(GCM_TAG_LENGTH, ivBytes));
26 cipher.updateAAD(authenticationTag.getBytes(Charset.forName("UTF-8")));
27 byte[] decryptedByte = cipher.doFinal(encryptedTextBytes);
28 String decryptedMessage = new String(decryptedByte, Charset.forName("UTF-8"));
29 return decryptedMessage;
30 }