· 5 years ago · Dec 17, 2019, 02:26 AM
1public class Encryptor {
2
3 private static String encrypt(String seed, String cleartext) throws Exception {
4 byte[] rawKey = getRawKey(seed.getBytes());
5 byte[] result = encrypt(rawKey, cleartext.getBytes());
6 return toHex(result);
7 }
8
9 private static String decrypt(String seed, String encrypted) throws Exception {
10 byte[] rawKey = getRawKey(seed.getBytes());
11 byte[] enc = toByte(encrypted);
12 byte[] result = decrypt(rawKey, enc);
13 return new String(result);
14 }
15
16 private static byte[] getRawKey(byte[] seed) throws Exception {
17 KeyGenerator kgen = KeyGenerator.getInstance("AES");
18 @SuppressLint("DeletedProvider") SecureRandom sr = SecureRandom.getInstance("SHA1PRNG","Crypto");
19 sr.setSeed(seed);
20 kgen.init(128, sr); // 192 and 256 bits may not be available
21 SecretKey skey = kgen.generateKey();
22 return skey.getEncoded();
23 }
24
25
26 private static byte[] encrypt(byte[] raw, byte[] clear) throws Exception {
27 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
28 Cipher cipher = Cipher.getInstance("AES");
29 cipher.init(Cipher.ENCRYPT_MODE, skeySpec);
30 return cipher.doFinal(clear);
31 }
32
33 private static byte[] decrypt(byte[] raw, byte[] encrypted) throws Exception {
34 SecretKeySpec skeySpec = new SecretKeySpec(raw, "AES");
35 Cipher cipher = Cipher.getInstance("AES");
36 cipher.init(Cipher.DECRYPT_MODE, skeySpec);
37 return cipher.doFinal(encrypted);
38 }
39
40 public static String toHex(String txt) {
41 return toHex(txt.getBytes());
42 }
43 public static String fromHex(String hex) {
44 return new String(toByte(hex));
45 }
46
47 private static byte[] toByte(String hexString) {
48 int len = hexString.length()/2;
49 byte[] result = new byte[len];
50 for (int i = 0; i < len; i++)
51 result[i] = Integer.valueOf(hexString.substring(2*i, 2*i+2), 16).byteValue();
52 return result;
53 }
54
55 private static String toHex(byte[] buf) {
56 if (buf == null)
57 return "";
58 StringBuffer result = new StringBuffer(2*buf.length);
59 for (byte b : buf) {
60 appendHex(result, b);
61 }
62 return result.toString();
63 }
64 private final static String HEX = "0123456789ABCDEF";
65 private static void appendHex(StringBuffer sb, byte b) {
66 sb.append(HEX.charAt((b>>4)&0x0f)).append(HEX.charAt(b&0x0f));
67 }
68
69 public static String encrypt(String strNormalText){
70 String seedValue = "jtiSeed2019";
71 String normalTextEnc="";
72 try {
73 normalTextEnc = Encryptor.encrypt(seedValue, strNormalText);
74 } catch (Exception e) {
75 e.printStackTrace();
76 }
77 return normalTextEnc;
78 }
79 public static String decrypt(String strEncryptedText){
80 String seedValue = "jtiSeed2019";
81 String strDecryptedText="";
82 try {
83 strDecryptedText = Encryptor.decrypt(seedValue, strEncryptedText);
84 } catch (Exception e) {
85 e.printStackTrace();
86 }
87 return strDecryptedText;
88 }
89}