2
peternameyakj
2024-08-14 9bcf85f8d8f9b503e386a67924f5943cd77bd813
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
package kernel.util;
 
import java.security.Key;
 
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
 
public class ImageVerificationEndecrypt {
    /**
     * 加密数据
     * 
     * @param encryptString 注意:这里的数据长度只能为8的倍数
     * @param encryptKey
     * @return
     * @throws Exception
     */
    public static String encryptDES(String encryptString, String encryptKey) throws Exception {
        SecretKeySpec key = new SecretKeySpec(getKey(encryptKey), "DES");
//        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        byte[] encryptedData = cipher.doFinal(encryptString.getBytes());
        return ConvertUtil.bytesToHexString(encryptedData);
    }
 
    /**
     * 自定义一个key
     * 
     * @param string
     */
    public static byte[] getKey(String keyRule) {
        Key key = null;
        byte[] keyByte = keyRule.getBytes();
        // 创建一个空的八位数组,默认情况下为0
        byte[] byteTemp = new byte[8];
        // 将用户指定的规则转换成八位数组
        for (int i = 0; i < byteTemp.length && i < keyByte.length; i++) {
            byteTemp[i] = keyByte[i];
        }
        key = new SecretKeySpec(byteTemp, "DES");
        return key.getEncoded();
    }
 
    /***
     * 解密数据
     * 
     * @param decryptString
     * @param decryptKey
     * @return
     * @throws Exception
     */
    public static String decryptDES(String decryptString, String decryptKey) throws Exception {
        SecretKeySpec key = new SecretKeySpec(getKey(decryptKey), "DES");
//        Cipher cipher = Cipher.getInstance("DES/ECB/NoPadding");
        Cipher cipher = Cipher.getInstance("DES/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, key);
        byte decryptedData[] = cipher.doFinal(ConvertUtil.hexStringToByte(decryptString));
        return new String(decryptedData);
    }
 
//    public static void main(String[] args) throws Exception {
//        String clearText = "spri"; // 这里的数据长度必须为8的倍数
//        String key = "12345678image_key";
//        System.out.println("明文:" + clearText + "\n密钥:" + key);
//        String encryptText = encryptDES(clearText, key);
//        System.out.println("加密后:" + encryptText);
//        String decryptText = decryptDES(encryptText, key);
//        System.out.println("解密后:" + decryptText);
//    }
}