· 7 years ago · Nov 12, 2018, 12:56 PM
1public class AesCipher {
2
3 private static final String INIT_VECTOR = "ItIsOurBigSecret";
4
5 // зашифрование
6 static byte[] encrypt(byte[] secretKey, byte[] plainText, String mode) {
7
8 try {
9 if (!isKeyLengthValid(secretKey)) {
10 throw new Exception("Длина ключа должна быть 128, 192 или 256 бит!");
11 }
12
13 IvParameterSpec ivParameterSpec = new IvParameterSpec(INIT_VECTOR.getBytes());
14 SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");
15
16 Cipher cipher = Cipher.getInstance("AES/" + mode + "/PKCS5Padding");
17 if (mode.equals("ECB"))
18 cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec);
19 else
20 cipher.init(Cipher.ENCRYPT_MODE, secretKeySpec, ivParameterSpec);
21
22 return cipher.doFinal(plainText);
23 } catch (Throwable cause) {
24 System.out.print(cause.getMessage());
25 }
26
27 return null;
28 }
29
30
31 // дешифрование
32 static byte[] decrypt(byte[] secretKey, byte[] cipherText, String mode) {
33
34 try {
35 if (!isKeyLengthValid(secretKey)) {
36 throw new Exception("Длина ключа должна быть 128, 192 или 256 бит!");
37 }
38
39 IvParameterSpec ivParameterSpec = new IvParameterSpec(INIT_VECTOR.getBytes());
40 SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey, "AES");
41
42 Cipher cipher = Cipher.getInstance("AES/" + mode + "/PKCS5Padding");
43 if (mode.equals("ECB"))
44 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec);
45 else
46 cipher.init(Cipher.DECRYPT_MODE, secretKeySpec, ivParameterSpec);
47
48 return cipher.doFinal(cipherText);
49 } catch (Throwable cause) {
50 System.out.print(cause.getMessage());
51 Controller.ShowMessage(cause.getMessage());
52 }
53
54 return null;
55 }
56
57
58 // проверка длины ключа
59 private static boolean isKeyLengthValid(byte[] key) {
60 return key.length == 16 || key.length == 24 || key.length == 32;
61 }