· 7 years ago · Aug 09, 2018, 08:26 AM
1package id.comrade.utility;
2
3/**
4 * Created by user on 12/16/2016.
5 */
6import android.util.Base64;
7
8import java.io.UnsupportedEncodingException;
9import java.security.MessageDigest;
10import java.security.NoSuchAlgorithmException;
11import java.util.Arrays;
12import java.util.Random;
13
14import javax.crypto.Cipher;
15import javax.crypto.spec.SecretKeySpec;
16
17
18public class AESEncrypt {
19
20 private static SecretKeySpec secretKey;
21 private static byte[] key;
22
23 public static void setKey(String myKey)
24 {
25 MessageDigest sha = null;
26 try {
27 key = myKey.getBytes("UTF-8");
28 sha = MessageDigest.getInstance("SHA-1");
29 key = sha.digest(key);
30 key = Arrays.copyOf(key, 16);
31 secretKey = new SecretKeySpec(key, "AES");
32 }
33 catch (NoSuchAlgorithmException e) {
34 e.printStackTrace();
35 }
36 catch (UnsupportedEncodingException e) {
37 e.printStackTrace();
38 }
39 }
40
41 public static String encrypt(String strToEncrypt, String secret)
42 {
43 try
44 {
45 setKey(secret);
46 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5Padding");
47 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
48 return Base64.encodeToString(cipher.doFinal(strToEncrypt.getBytes("UTF-8")),Base64.DEFAULT);
49 }
50 catch (Exception e)
51 {
52 System.out.println("Error while encrypting: " + e.toString());
53 }
54 return null;
55 }
56
57 public static String decrypt(String strToDecrypt, String secret)
58 {
59 try
60 {
61 setKey(secret);
62 Cipher cipher = Cipher.getInstance("AES/ECB/PKCS5PADDING");
63 cipher.init(Cipher.DECRYPT_MODE, secretKey);
64 byte[] hasil = Base64.decode(strToDecrypt,Base64.DEFAULT);
65 return new String(cipher.doFinal(hasil),"UTF-8");
66 }
67 catch (Exception e)
68 {
69 System.out.println("Error while decrypting: " + e.toString());
70 }
71 return null;
72 }
73
74 public static String randomKey() {
75 String SALTCHARS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";
76 StringBuilder salt = new StringBuilder();
77 Random rnd = new Random();
78 while (salt.length() < 12) {
79 int index = (int) (rnd.nextFloat() * SALTCHARS.length());
80 salt.append(SALTCHARS.charAt(index));
81 }
82 String saltStr = salt.toString();
83 return saltStr;
84
85 }
86}