DesUtil.java
3.07 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
77
78
79
80
81
82
83
84
85
86
87
88
89
package cn.csbr.configenc;
import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
/*
des加密
*/
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class DesUtil {
public final static String KEY = "3cbc87a4ba60488aae7e60cc7caf65f";
/**
* DES加密
*
*
* @param data
* 待加密字符串
* @param key
* 校验位
* @return
*/
public static String encrypt(String data,String key) {
String encryptedData = null;
try {
// DES算法要求有一个可信任的随机数源
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(key.getBytes());
// 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(deskey);
// 加密对象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.ENCRYPT_MODE, secretKey, sr);
// 加密,并把字节数组编码成字符串
encryptedData = new sun.misc.BASE64Encoder().encode(cipher.doFinal(data.getBytes()));
} catch (Exception e) {
throw new RuntimeException("加密错误,错误信息:", e);
}
return encryptedData;
}
/**
* DES解密
*
*
* @param cryptData
* 待解密密文
* @param key
* 校验位
* @return
*/
public static String decrypt(String cryptData,String key) {
String decryptedData = null;
try {
// DES算法要求有一个可信任的随机数源
// System.out.println("开始解密");
SecureRandom sr = new SecureRandom();
DESKeySpec deskey = new DESKeySpec(key.getBytes());
// 创建一个密匙工厂,然后用它把DESKeySpec转换成一个SecretKey对象
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
SecretKey secretKey = keyFactory.generateSecret(deskey);
// 解密对象
Cipher cipher = Cipher.getInstance("DES");
cipher.init(Cipher.DECRYPT_MODE, secretKey, sr);
// 把字符串解码为字节数组,并解密
decryptedData = new String(cipher.doFinal(new sun.misc.BASE64Decoder().decodeBuffer(cryptData)));
} catch (Exception e) {
throw new RuntimeException("解密错误,错误信息:", e);
}
return decryptedData;
}
public static void main(String[] args) {
System.out.println("url::"+encrypt("jdbc:mysql://127.0.0.1:3306/hcg?autoReconnect=true&autoReconnectForPools=true&useUnicode=true&characterEncoding=utf8&useSSL=false",KEY));
System.out.println("username::"+encrypt("root",KEY));
System.out.println("password::"+encrypt("123456",KEY));
}
}