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