· 7 years ago · Apr 20, 2018, 06:00 PM
1package com.example.chernovik;
2
3
4import android.util.Base64;
5
6
7
8import javax.crypto.Cipher;
9import javax.crypto.spec.IvParameterSpec;
10import javax.crypto.spec.SecretKeySpec;
11
12
13
14
15public class AesCrypto {
16
17 String key = "0123456789abcdef"; // 128 bit key
18 String initVector = "abcdef9876543210"; // 16 bytes IV, it is recommended to use a different random IV for every message!
19
20 private static String CIPHER_NAME = "AES/CBC/PKCS5PADDING";
21 private static int CIPHER_KEY_LEN = 16; //128 bits
22
23 /**
24 * Encrypt data using AES Cipher (CBC) with 128 bit key
25 *
26 * @param key - key to use should be 16 bytes long (128 bits)
27 * @param iv - initialization vector
28 * @param data - data to encrypt
29 * @return encryptedData data in base64 encoding with iv attached at end after a :
30 */
31 public static String encrypt(String key, String iv, String data) {
32
33 try {
34 IvParameterSpec ivSpec = new IvParameterSpec(iv.getBytes("UTF-8"));
35 SecretKeySpec secretKey = new SecretKeySpec(fixKey(key).getBytes("UTF-8"), "AES");
36
37 Cipher cipher = Cipher.getInstance(AesCrypto.CIPHER_NAME);
38 cipher.init(Cipher.ENCRYPT_MODE, secretKey, ivSpec);
39
40 byte[] encryptedData = cipher.doFinal((data.getBytes()));
41
42 String encryptedDataInBase64 = Base64.getEncoder().encodeToString(encryptedData);
43 String ivInBase64 = Base64.getEncoder().encodeToString(iv.getBytes("UTF-8"));
44
45 return encryptedDataInBase64 + ":" + ivInBase64;
46
47 } catch (Exception ex) {
48 throw new RuntimeException(ex);
49 }
50 }
51
52 private static String fixKey(String key) {
53
54 if (key.length() < AesCrypto.CIPHER_KEY_LEN) {
55 int numPad = AesCrypto.CIPHER_KEY_LEN - key.length();
56
57 for (int i = 0; i < numPad; i++) {
58 key += "0"; //0 pad to len 16 bytes
59 }
60
61 return key;
62
63 }
64
65 if (key.length() > AesCrypto.CIPHER_KEY_LEN) {
66 return key.substring(0, CIPHER_KEY_LEN); //truncate to 16 bytes
67 }
68
69 return key;
70 }
71
72 /**
73 * Decrypt data using AES Cipher (CBC) with 128 bit key
74 *
75 * @param key - key to use should be 16 bytes long (128 bits)
76 * @param data - encrypted data with iv at the end separate by :
77 * @return decrypted data string
78 */
79
80 public static String decrypt(String key, String data) {
81
82 try {
83 String[] parts = data.split(":");
84
85 IvParameterSpec iv = new IvParameterSpec(Base64.getDecoder().decode(parts[1]));
86 SecretKeySpec secretKey = new SecretKeySpec(key.getBytes("UTF-8"), "AES");
87
88 Cipher cipher = Cipher.getInstance(AesCrypto.CIPHER_NAME);
89 cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);
90
91 byte[] decodedEncryptedData = Base64.getDecoder().decode(parts[0]);
92
93 byte[] original = cipher.doFinal(decodedEncryptedData);
94
95 return new String(original);
96 } catch (Exception ex) {
97 throw new RuntimeException(ex);
98 }
99 }
100}