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