· 9 years ago · Oct 20, 2016, 08:02 PM
1public String harden(String unencryptedString) throws NoSuchAlgorithmException, UnsupportedEncodingException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
2 MessageDigest md = MessageDigest.getInstance("md5");
3 byte[] digestOfPassword = md.digest(key.getBytes("utf-8"));
4 byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
5
6 for (int j = 0, k = 16; j < 8;) {
7 keyBytes[k++] = keyBytes[j++];
8 }
9
10 SecretKey secretKey = new SecretKeySpec(keyBytes, "DESede");
11 Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
12 cipher.init(Cipher.ENCRYPT_MODE, secretKey);
13
14 byte[] plainTextBytes = unencryptedString.getBytes("utf-8");
15 byte[] buf = cipher.doFinal(plainTextBytes);
16 byte[] base64Bytes = Base64.encodeBase64(buf);
17 String base64EncryptedString = new String(base64Bytes);
18
19 return base64EncryptedString;
20}
21
22public String soften(String encryptedString) throws UnsupportedEncodingException, NoSuchAlgorithmException, NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException {
23 if(encryptedString == null)
24 {
25 return "";
26 }
27 byte[] message = Base64.decodeBase64(encryptedString.getBytes("utf-8"));
28
29 MessageDigest md = MessageDigest.getInstance("MD5");
30 byte[] digestOfPassword = md.digest(key.getBytes("utf-8"));
31 byte[] keyBytes = Arrays.copyOf(digestOfPassword, 24);
32
33 for (int j = 0, k = 16; j < 8;) {
34 keyBytes[k++] = keyBytes[j++];
35 }
36
37 SecretKey secretKey = new SecretKeySpec(keyBytes, "DESede");
38
39 Cipher decipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
40 decipher.init(Cipher.DECRYPT_MODE, secretKey);
41
42 byte[] plainText = decipher.doFinal(message);
43
44 return new String(plainText, "UTF-8");
45
46}