forked from AlEinstein/javaCode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathDESUtil.java
More file actions
82 lines (74 loc) · 2.26 KB
/
Copy pathDESUtil.java
File metadata and controls
82 lines (74 loc) · 2.26 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
package common.utils;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.security.Key;
/**
* DES加密。
* create by mulin on 2018/11/28.
*
* 注:密钥必须为8位。默认密钥为A1B4C2D3。
*/
public class DESUtil {
public static String key = "A1B4C2D3";
private static final String CIPHER_ALGORITHM = "DES/CBC/PKCS5Padding";
private static SecretKey keyGenerator(String keyStr) throws Exception {
DESKeySpec desKey = new DESKeySpec(keyStr.getBytes("UTF-8")); //DESKeySpec
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
return keyFactory.generateSecret(desKey);
}
/**
* 加密
*
* @param data
* @param key 长度必须为8位
* @return
* @throws Exception
*/
public static String encrypt(String data, String key) throws Exception {
Key deskey = keyGenerator(key);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.ENCRYPT_MODE, deskey, iv);
byte[] results = cipher.doFinal(data.getBytes("UTF-8"));
return Base64.encodeBase64String(results);
}
/**
* 加密
*
* @param data
* @return
* @throws Exception
*/
public static String encrypt(String data) throws Exception {
return encrypt(data, key);
}
/**
* 解密
*
* @param data
* @param key 密钥长度为8位
* @return
* @throws Exception
*/
public static String decrypt(String data, String key) throws Exception {
Key deskey = keyGenerator(key);
IvParameterSpec iv = new IvParameterSpec(key.getBytes("UTF-8"));
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
cipher.init(Cipher.DECRYPT_MODE, deskey, iv);
return new String(cipher.doFinal(Base64.decodeBase64(data)));
}
/**
* 解密
*
* @param data
* @return
* @throws Exception
*/
public static String decrypt(String data) throws Exception {
return decrypt(data, key);
}
}