· 7 years ago · Oct 18, 2018, 05:44 PM
1import java.io.*;
2import java.util.*;
3import javax.crypto.*;
4
5public class AES
6{
7 Cipher ecipher,dcipher;
8 public AES(SecretKey key)
9 {
10 try
11 {
12 ecipher=Cipher.getInstance("AES");
13 ecipher.init(Cipher.ENCRYPT_MODE,key);
14 dcipher=Cipher.getInstance("AES");
15 dcipher.init(Cipher.DECRYPT_MODE,key);
16 }
17 catch(Exception e)
18 {
19 System.out.println("Exception occur:"+e);
20 }
21 }
22 public String encrypt(String str)
23 {
24 try
25 {
26 byte[] utf8=str.getBytes("UTF8");
27 byte[] enc=ecipher.doFinal(utf8);
28 return new sun.misc.BASE64Encoder().encode(enc);
29 }
30 catch(Exception e)
31 {
32 System.out.println("Exception occur:"+e);
33 }
34 return null;
35 }
36 public String decrypt(String str)
37 {
38 try
39 {
40 byte[] dec=new sun.misc.BASE64Decoder().decodeBuffer(str);
41 byte[] utf8=dcipher.doFinal(dec);
42 return new String(utf8,"UTF8");
43 }
44 catch(Exception e)
45 {
46 System.out.println("Exception occur:"+e);
47 }
48 return null;
49 }
50 public static void main(String args[])
51 {
52 try
53 {
54 System.out.println("\n\t=========AES================\n");
55 SecretKey key=KeyGenerator.getInstance("AES").generateKey();
56 AES aes=new AES(key);
57
58
59 System.out.print("\tEnter the string to encrypted:");
60 Scanner sc=new Scanner(System.in);
61 String input=sc.nextLine();
62 String encrypt=aes.encrypt(input);
63 String decrypt=aes.decrypt(encrypt);
64
65 System.out.println("\n\tOriginal string is:"+input);
66 System.out.println("\tEncrypted string is : "+encrypt);
67 System.out.println("\tDecrypted String is : "+decrypt);
68 }
69 catch(Exception e)
70 {
71 System.out.println("Exception occur:"+e);
72 }
73 }
74}