· 6 years ago · Mar 20, 2019, 03:06 PM
1public static String encryptID(String id) {
2
3 String encryptedID = "";
4
5 try {
6 SecretKeySpec secretKey = new SecretKeySpec(Constants.ID_KEY.getBytes("UTF-8"), "AES");
7 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
8 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
9
10 encryptedID = new BASE64Encoder().encodeBuffer(cipher.doFinal(id.getBytes("UTF-8")));
11 } catch (Exception e) {
12 log.error("Encryption error. Unable to encrypt ID.", e);
13 encryptedID = "ERROR";
14 }
15
16 return encryptedID;
17}
18
19public static String decryptID(String encryptedID) {
20
21 String decryptedID = "";
22
23 try {
24 SecretKeySpec secretKey = new SecretKeySpec(Constants.ID_KEY.getBytes("UTF-8"), "AES");
25 Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
26 cipher.init(Cipher.ENCRYPT_MODE, secretKey, new IvParameterSpec(new byte[cipher.getBlockSize()]));
27
28 byte[] decodedValue = cipher.doFinal(new BASE64Decoder().decodeBuffer(encryptedID));
29 decryptedID = new String(decodedValue);
30
31 } catch (Exception e) {
32 e.printStackTrace();
33 }
34 return decryptedID;
35
36}
37
38@Test
39 public void testEncryption() {
40
41 String ecryptedID = DataUtil.encryptID("123456789");
42 System.out.println(ecryptedID);
43 System.out.println(DataUtil.decryptID(ecryptedID));
44
45}