· 5 years ago · Nov 28, 2019, 06:04 AM
1 public byte[] doEncrypt(String key, byte[] plaintext,byte[] aad) {
2
3 SecureRandom secureRandom = new SecureRandom();
4
5 try {
6 byte [] iv = new byte[IV_LENGTH_BIT];
7 secureRandom.nextBytes(iv);
8
9 SecretKey secretKey=generateSecretKey(key,iv);
10
11 Cipher cipher = Cipher.getInstance(ALGORITHM);
12 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
13
14 cipher.updateAAD(aad);
15
16 byte[] encrypted = cipher.doFinal(plaintext);
17
18 ByteBuffer byteBuffer = ByteBuffer.allocate(4 + iv.length + encrypted.length);
19 Log.d(TAG,"ENd_iv="+iv.length);
20 byteBuffer.putInt(iv.length);
21 byteBuffer.put(iv);
22 byteBuffer.put(encrypted);
23 Log.d(TAG, byteBuffer.toString());
24 return byteBuffer.array();
25
26 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | BadPaddingException | IllegalBlockSizeException | InvalidAlgorithmParameterException | InvalidKeySpecException e) {
27 throw new RuntimeException(e);
28 }
29 }
30
31
32 public static byte[] doDecrypt(String key, String enc_data,byte[] aad) {
33
34 try {
35 byte[] encypt_data=Base64.decode(enc_data,Base64.DEFAULT);
36 ByteBuffer byteBuffer = ByteBuffer.wrap(encypt_data);
37 int ivLength = byteBuffer.getInt();
38 Log.d(TAG,"IV len="+ivLength);
39 if(ivLength < 12 || ivLength >= 16) { // check input parameter
40 throw new IllegalArgumentException("Invalid iv length");
41 }
42 byte[] iv = new byte[ivLength];
43 byteBuffer.get(iv);
44
45 byte[] encrypted = new byte[byteBuffer.remaining()];
46 byteBuffer.get(encrypted);
47 SecretKey secretKey=generateSecretKey(key,iv);
48 Cipher cipher = Cipher.getInstance(ALGORITHM);
49 cipher.init(Cipher.DECRYPT_MODE, secretKey, new GCMParameterSpec(TAG_LENGTH_BIT, iv));
50 cipher.updateAAD(aad);
51
52 Log.d(TAG,"data="+enc_data);
53 return cipher.doFinal(encypt_data);
54
55
56 } catch (NoSuchAlgorithmException | NoSuchPaddingException | InvalidKeyException | InvalidAlgorithmParameterException | BadPaddingException | IllegalBlockSizeException | InvalidKeySpecException e) {
57 throw new RuntimeException(e);
58 }
59 }