· 6 years ago · Feb 18, 2019, 02:10 PM
1package AesEncryption;
2
3import javax.crypto.Cipher;
4import javax.crypto.spec.SecretKeySpec;
5import java.util.Random;
6
7public class AdvancedEncryptionStandard {
8 private byte[] key;
9 private static final String ALGORITHM = "AES";
10
11 // Encrypts the given plain text
12 public byte[] encrypt(String plainText) throws Exception {
13 SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
14 Cipher cipher = Cipher.getInstance(ALGORITHM);
15 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
16 byte[] encryptedData = cipher.doFinal(plainText.getBytes("UTF-8"));
17 return encryptedData;
18 }
19
20 // Decrypts the given byte array
21 public String decrypt(byte[] cipherText) throws Exception {
22 SecretKeySpec secretKey = new SecretKeySpec(key, ALGORITHM);
23 Cipher cipher = Cipher.getInstance(ALGORITHM);
24 cipher.init(Cipher.DECRYPT_MODE, secretKey);
25 String decryptedData = new String(cipher.doFinal(cipherText));
26 return decryptedData;
27 }
28
29 // creates random key for aes encryption
30 public static byte[] createRandomKey(int size) {
31 String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890abcdefghijklmnopqrstuvwxyz!§$%&/()=?*'#+-:;.,_";
32 StringBuilder salt = new StringBuilder();
33 Random rnd = new Random();
34 while (salt.length() < size) { // length of key
35 int index = (int) (rnd.nextFloat() * SALTCHARS.length());
36 salt.append(SALTCHARS.charAt(index));
37 }
38
39 return salt.toString().getBytes();
40 }
41
42 public AdvancedEncryptionStandard(byte[] key) {
43 this.key = key;
44 }
45}