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