· 6 years ago · Mar 05, 2019, 06:34 PM
1public static byte[] decryptToByteArray(byte[] cipherText, byte[] secretKey)
2 throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
3 BadPaddingException, InvalidAlgorithmParameterException {
4 ByteArrayOutputStream baos = new ByteArrayOutputStream();
5 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
6 SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");
7 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, new IvParameterSpec(new byte[16]));
8 for (int i = 0; i < cipherText.length; i += 16) {
9 try {
10 baos.write(cipher.doFinal(Arrays.copyOfRange(cipherText, i, i + 16)));
11
12 } catch (IOException e) {
13 // TODO Auto-generated catch block
14 e.printStackTrace();
15 }
16
17 }
18 return baos.toByteArray();
19 }
20 public static byte[] encryptToByteArray(byte[] data, byte[] secretKey)
21 throws NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException,
22 BadPaddingException, InvalidAlgorithmParameterException {
23 ByteArrayOutputStream baos = new ByteArrayOutputStream();
24 Cipher cipher = Cipher.getInstance("AES/CBC/NoPadding");
25 SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");
26 cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, new IvParameterSpec(new byte[16]));
27 for (int i = 0; i < data.length; i += 16) {
28 try {
29 baos.write(cipher.doFinal(Arrays.copyOfRange(data, i, i + 16)));
30
31 } catch (IOException e) {
32 // TODO Auto-generated catch block
33 e.printStackTrace();
34 }
35
36 }
37 return baos.toByteArray();
38 }