· 6 years ago · Jun 27, 2019, 10:42 AM
1@Service
2 public class EncryptionUtil {
3
4private static final Logger log = LogManager.getLogger(EncryptionUtil.class);
5
6private Cipher ecipher;
7private Cipher dcipher;
8@Autowired
9private StringUtils stringUtils;
10@Autowired
11GpsCacheManager gpsCacheManager;
12
13public EncryptionUtil() throws Exception {
14 ecipher = Cipher.getInstance("DES");
15 dcipher = Cipher.getInstance("DES");
16 initCipher();
17 }
18
19
20private void initCipher(){
21 try{
22 String response = “[-3232, -34, -98, 111, -222, 33, -22, 55]”;
23 String[] byteValues = response.substring(1, response.length() - 1).split(",");
24 byte[] bytes = new byte[byteValues.length];
25 for (int i=0, len=bytes.length; i<len; i++) {
26 bytes[i] = Byte.parseByte(byteValues[i].trim());
27 }
28
29 SecretKey key = new SecretKeySpec(bytes, "DES");
30 ecipher.init(Cipher.ENCRYPT_MODE, key);
31 dcipher.init(Cipher.DECRYPT_MODE, key);
32 }catch(Exception e){
33 log.error(e.getMessage(), e);
34 }
35}
36
37
38
39 public String encryptUTF8(String str) throws Exception {
40 // Encode the string into bytes using utf-8
41 byte[] utf8 = str.getBytes("UTF8");
42
43 // Encrypt
44 byte[] enc = ecipher.doFinal(utf8);
45 // Encode bytes to base64 to get a string
46 return new String(Base64.encodeBase64(enc));
47}
48
49 public String decryptUTF8(String str) throws Exception {
50
51 if(stringUtils == null) {
52 stringUtils = new StringUtils();
53 }
54 //do not decrypt if a valid email.
55 if(stringUtils.isValidEmail(str)) {
56 return str;
57 }
58 // Decode base64 to get bytes
59 byte[] dec = Base64.decodeBase64(str.getBytes());
60
61 byte[] utf8 = null;
62 try {
63 utf8 = dcipher.doFinal(dec);
64 }
65 catch (IllegalBlockSizeException e) {
66 return str;
67 }
68 // Decode using utf-8
69 return new String(utf8, "UTF8");
70}