· 8 years ago · Jan 25, 2018, 09:16 PM
1public class AESEncryptor {
2 private static final String ALGO = "AES";
3 private static final String keyVal = "!5Po4@j82Adsu39/*na3n5";
4
5 public static String encrypt(String data) {
6 try {
7 Key key = genKey();
8 Cipher c = Cipher.getInstance(ALGO);
9 c.init(Cipher.ENCRYPT_MODE, key);
10 byte[] encVal = c.doFinal(data.getBytes());
11 return Base64.encodeBase64String(encVal);
12 } catch (Exception e) {
13 e.printStackTrace();
14 }
15 return null;
16 }
17
18 public static String decrypt (String encryptedData) throws Exception{
19 Key key = genKey();
20 Cipher c = Cipher.getInstance(ALGO);
21 c.init(Cipher.DECRYPT_MODE, key);
22 byte[] data = Base64.decodeBase64(encryptedData);
23 byte[] decByptes = c.doFinal(data);
24 return new String(decByptes);
25 }
26
27 private static Key genKey() throws Exception {
28 fixKeyLength();
29 return new SecretKeySpec(keyVal.getBytes(), ALGO);
30 }
31}
32
33KeyGenerator keyGen = KeyGenerator.getInstance("AES");
34 keyGen.init(256);
35 SecretKey key = keyGen.generateKey();
36
37 final byte[] nonce = new byte[32];
38 SecureRandom random = SecureRandom.getInstanceStrong();
39 random.nextBytes(nonce);
40 Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");
41 GCMParameterSpec spec = new GCMParameterSpec(16 * 8, nonce);
42 cipher.init(Cipher.ENCRYPT_MODE, key, spec);