1+ import java .io .UnsupportedEncodingException ;
2+ import java .security .MessageDigest ;
3+ import java .security .NoSuchAlgorithmException ;
4+ import java .util .Arrays ;
5+ import java .util .Base64 ;
6+
7+ import javax .crypto .Cipher ;
8+ import javax .crypto .spec .SecretKeySpec ;
9+
10+ public class AES {
11+
12+ private static SecretKeySpec secretKey ;
13+ private static byte [] key ;
14+
15+ public static void setKey (String myKey )
16+ {
17+ MessageDigest sha = null ;
18+ try {
19+ key = myKey .getBytes ("UTF-8" );
20+ sha = MessageDigest .getInstance ("SHA-1" );
21+ key = sha .digest (key );
22+ key = Arrays .copyOf (key , 16 );
23+ secretKey = new SecretKeySpec (key , "AES" );
24+ }
25+ catch (NoSuchAlgorithmException e ) {
26+ e .printStackTrace ();
27+ }
28+ catch (UnsupportedEncodingException e ) {
29+ e .printStackTrace ();
30+ }
31+ }
32+
33+ public static String encrypt (String strToEncrypt , String secret )
34+ {
35+ try
36+ {
37+ setKey (secret );
38+ Cipher cipher = Cipher .getInstance ("AES/ECB/PKCS5Padding" );
39+ cipher .init (Cipher .ENCRYPT_MODE , secretKey );
40+ return Base64 .getEncoder ().encodeToString (cipher .doFinal (strToEncrypt .getBytes ("UTF-8" )));
41+ }
42+ catch (Exception e )
43+ {
44+ System .out .println ("Found error while encrypting: " + e .toString ());
45+ }
46+ return null ;
47+ }
48+
49+ public static String decrypt (String strToDecrypt , String secret )
50+ {
51+ try
52+ {
53+ setKey (secret );
54+ Cipher cipher = Cipher .getInstance ("AES/ECB/PKCS5PADDING" );
55+ cipher .init (Cipher .DECRYPT_MODE , secretKey );
56+ return new String (cipher .doFinal (Base64 .getDecoder ().decode (strToDecrypt )));
57+ }
58+ catch (Exception e )
59+ {
60+ System .out .println ("Found error while decrypting: " + e .toString ());
61+ }
62+ return null ;
63+ }
64+ }
65+
66+ /* TESTCODE TO RUN:
67+
68+ public static void main(String[] args)
69+ {
70+ final String secretKey = "donttellanyone!";
71+
72+ String originalString = "THISISASTRING";
73+ String encryptedString = AES.encrypt(originalString, secretKey) ;
74+ String decryptedString = AES.decrypt(encryptedString, secretKey) ;
75+
76+ System.out.println(originalString);
77+ System.out.println(encryptedString);
78+ System.out.println(decryptedString);
79+ }
80+
81+ */
0 commit comments