-
Notifications
You must be signed in to change notification settings - Fork 0
/
Enc.java
77 lines (66 loc) · 2.56 KB
/
Enc.java
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
77
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Date;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;
public class AESUtils {
private static final String KEY_ALGORITHM = "AES";
private static final String DEFAULT_CIPHER_ALGORITHM = "AES/ECB/PKCS5Padding";
public static String encrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
byte[] byteContent = content.getBytes("utf-8");
cipher.init(Cipher.ENCRYPT_MODE, getSecretKey());
byte[] result = cipher.doFinal(byteContent);
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
public static String decrypt(String content, String password) {
try {
Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, getSecretKey());
byte[] result = cipher.doFinal(Base64.decode(content));
return new String(result, "utf-8");
} catch (Exception ex) {
ex.printStackTrace();
}
return null;
}
private static SecretKeySpec getSecretKey() {
KeyGenerator kg = null;
String password="1231231231231231";
try {
kg = KeyGenerator.getInstance(KEY_ALGORITHM);
SecureRandom random = SecureRandom.getInstance("SHA1PRNG");
random.setSeed(password.getBytes());
kg.init(128, random);
SecretKey secretKey = kg.generateKey();
System.out.println(secretKey);
return new SecretKeySpec(secretKey.getEncoded(), KEY_ALGORITHM);
} catch (NoSuchAlgorithmException ex) {
ex.printStackTrace();
}
return null;
}
public static void main(String[] args) {
String s = "abcdefghijklmnop";
System.out.println(s);
String s1= AESUtils.encrypt(s ,KEY);
System.out.println(s1);
try {
String s2= AESUtils.decryptPwd(s1,KEY);
System.out.println(s2);
} catch (Exception e) {
e.printStackTrace();
}
}
public static String decryptPwd(String encryptPwd,String key) throws Exception {
String str = AESUtils.decrypt(encryptPwd, key);
return str;
}
}