SymmetricCrypt.java
2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
/*
* Decompiled with CFR 0_118.
*
* Could not load the following classes:
* com.day.text.Text
* org.slf4j.Logger
* org.slf4j.LoggerFactory
*/
package com.day.cq.commons;
import com.day.text.Text;
import java.io.ByteArrayOutputStream;
import java.security.Key;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
public class SymmetricCrypt {
private static final Logger log = LoggerFactory.getLogger(SymmetricCrypt.class);
private static final int KEY_LENGTH = 8;
public static final String PREFIX = "{DES}";
public static String encrypt(String s) {
try {
SecretKey key = KeyGenerator.getInstance("DES").generateKey();
Cipher cipher = Cipher.getInstance("DES");
byte[] keyBytes = key.getEncoded();
byte[] data = s.getBytes("utf-8");
ByteArrayOutputStream out = new ByteArrayOutputStream(keyBytes.length + data.length);
out.write(keyBytes);
cipher.init(1, key);
out.write(cipher.update(data));
out.write(cipher.doFinal());
StringBuilder ret = new StringBuilder("{DES}");
for (byte b : out.toByteArray()) {
ret.append(Text.hexTable[b >> 4 & 15]).append(Text.hexTable[b & 15]);
}
return ret.toString();
}
catch (Exception e) {
log.warn("Unable to encrypt string: " + e);
return null;
}
}
public static String decrypt(String s) {
if (!s.startsWith("{DES}")) {
return null;
}
try {
byte[] data = new byte[(s.length() - "{DES}".length()) / 2];
int i = "{DES}".length();
int b = 0;
while (i < s.length()) {
data[b] = (byte)(Integer.parseInt(s.substring(i, i + 2), 16) & 255);
i += 2;
++b;
}
SecretKeySpec key = new SecretKeySpec(data, 0, 8, "DES");
Cipher cipher = Cipher.getInstance("DES");
ByteArrayOutputStream out = new ByteArrayOutputStream(data.length);
cipher.init(2, key);
out.write(cipher.update(data, 8, data.length - 8));
out.write(cipher.doFinal());
return out.toString("utf-8");
}
catch (Exception e) {
log.warn("Unable to decrypt data: " + e);
return null;
}
}
}