· 5 years ago · May 25, 2020, 10:16 AM
1public class AES_Encryption
2{
3 static String plainText = "Avinash@syntizen.com";
4
5 public static void main(String[] args) throws Exception
6 {
7 /* KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
8 keyGenerator.init(256);
9
10
11
12 // Generate Key
13 SecretKey key = keyGenerator.generateKey();
14
15
16
17 // Generating IV.
18 byte[] IV = new byte[16];
19 SecureRandom random = new SecureRandom();
20 random.nextBytes(IV);*/
21
22
23 String _key = "f379e0b661ae4650b19169e4d93665dc";//32 characters
24 String _iv = "0000000000000000";//16 characters
25 System.out.println("Original Text : "+plainText);
26
27 byte[] cipherText = encrypt(plainText.getBytes(),_key.getBytes(), _iv.getBytes());
28 System.out.println("Encrypted Text : "+Base64.getEncoder().encodeToString(cipherText));
29
30
31 String decryptedText = decrypt(cipherText,_key.getBytes(), _iv.getBytes());
32 System.out.println("DeCrypted Text : "+decryptedText);
33
34 }
35
36 public static byte[] encrypt (byte[] plaintext,byte[] key,byte[] IV ) throws Exception
37 {
38 //Get Cipher Instance
39 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
40
41 //Create SecretKeySpec
42 SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
43
44 //Create IvParameterSpec
45 IvParameterSpec ivSpec = new IvParameterSpec(IV);
46
47 //Initialize Cipher for ENCRYPT_MODE
48 cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
49
50 //Perform Encryption
51 byte[] cipherText = cipher.doFinal(plaintext);
52
53 return cipherText;
54 }
55
56 public static String decrypt (byte[] cipherText, byte[] key,byte[] IV) throws Exception
57 {
58 //Get Cipher Instance
59 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
60
61 //Create SecretKeySpec
62 SecretKeySpec keySpec = new SecretKeySpec(key, "AES");
63
64 //Create IvParameterSpec
65 IvParameterSpec ivSpec = new IvParameterSpec(IV);
66
67 //Initialize Cipher for DECRYPT_MODE
68 cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
69
70 //Perform Decryption
71 byte[] decryptedText = cipher.doFinal(cipherText);
72
73 return new String(decryptedText);
74 }
75}