DecryptUtils.java
2.45 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
package com.topdraw.dockingapi.util;
import org.apache.commons.codec.binary.Base64;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.Key;
/**
* 加解密工具
*
* @author chenwl
* @date 2020-11-08 12:36:47
*/
public abstract class DecryptUtils {
private static final Logger log = LoggerFactory.getLogger(DecryptUtils.class);
private static final String TRANSFORMATION_DES = "DES/ECB/PKCS5Padding";
private static final String ALGORITHM_DES = "DES";
/**
* DES 加密
*
* @param key 密钥,长度不能够小于8位字节
* @param plainText 明文
* @return 密文
*/
public static String encode(String key, String plainText) throws Exception {
return encode(key, plainText.getBytes());
}
/**
* DES 加密
*
* @param key 密钥,长度不能够小于8位字节
* @param plainBytes 明文字节数组
* @return 密文
*/
public static String encode(String key, byte[] plainBytes) throws Exception {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM_DES);
Key secretKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance(TRANSFORMATION_DES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey);
byte[] bytes = cipher.doFinal(plainBytes);
return new String(Base64.encodeBase64(bytes));
}
/**
* 解密
*
* @param key 密钥,长度不能够小于8位字节
* @param cipherText 密文
* @return 明文
*/
public static String decode(String key, String cipherText) throws Exception {
return decode(key, cipherText.getBytes());
}
/**
* DES 解密
*
* @param key 密钥,长度不能够小于8位字节
* @param cipherBytes 密文字节数组
* @return 明文
*/
private static String decode(String key, byte[] cipherBytes) throws Exception {
DESKeySpec dks = new DESKeySpec(key.getBytes());
SecretKeyFactory skf = SecretKeyFactory.getInstance(ALGORITHM_DES);
Key secretKey = skf.generateSecret(dks);
Cipher cipher = Cipher.getInstance(TRANSFORMATION_DES);
cipher.init(Cipher.DECRYPT_MODE, secretKey);
return new String(cipher.doFinal(Base64.decodeBase64(cipherBytes)));
}
}