· 9 years ago · Jan 18, 2017, 11:46 PM
1private SecretKey getKey() {
2 byte[] desKeyData = new byte[8];
3 for (int i = 0; i < 7; ++i) {
4 int j = i * 3;
5 desKeyData[i] = (byte)(key.charAt(j) ^ key.charAt(j + 2));
6 }
7 return new SecretKeySpec(desKeyData, "DES");
8}
9
10public byte[] encrypt(String password) {
11 if (password == null) {
12 return null;
13 }
14 byte[] encryptedBytes = password.getBytes();
15 if (!doEncryption) {
16 return encryptedBytes;
17 }
18 SecretKey key = this.getKey();
19 try {
20 Cipher cipher = Cipher.getInstance("DES");
21 cipher.init(1, key);
22 byte[] bytes = null;
23 try {
24 bytes = password.getBytes("UTF-8");
25 }
26 catch (UnsupportedEncodingException ex) {
27 // empty catch block
28 }
29 encryptedBytes = cipher.doFinal(bytes);
30 this.encrypted = true;
31 }
32
33public String decrypt(byte[] encryptedBytes) {
34 if (encryptedBytes == null) {
35 return null;
36 }
37 String password = null;
38 try {
39 password = new String(encryptedBytes, "UTF-8");
40 }
41 catch (UnsupportedEncodingException ex) {
42 // empty catch block
43 }
44 if (!doEncryption || !this.encrypted) {
45 return password;
46 }
47 SecretKey key = this.getKey();
48 try {
49 Cipher cipher = Cipher.getInstance("DES");
50 cipher.init(2, key);
51 password = new String(cipher.doFinal(encryptedBytes));
52 }
53 catch (NoSuchAlgorithmException e) {
54 logger.error((Object)e);
55 }
56 catch (InvalidKeyException e) {
57 logger.error((Object)e);
58 }
59 catch (NoSuchPaddingException e) {
60 logger.error((Object)e);
61 }
62 catch (IllegalBlockSizeException e) {
63 logger.error((Object)e);
64 }
65 catch (BadPaddingException e) {
66 logger.error((Object)e);
67 }
68 return password;
69}