admin
2021-03-18 b37275dba6b782bf3bb3817c4504f6cdef1bef7c
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
package com.yeshi.buwan.util;
 
import java.security.InvalidKeyException;
import java.security.Key;
import java.security.NoSuchAlgorithmException;
import java.security.spec.AlgorithmParameterSpec;
import java.security.spec.InvalidKeySpecException;
 
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import javax.persistence.Entity;
 
import com.sun.org.apache.xerces.internal.impl.dv.util.Base64;
 
@Entity
public class DESUtil {
    /**
     * [加密]DES-->BASE64-->密文
     * 
     * [解密]BASE64->DES-->明文
     * 
     * 秘钥和向量要双方约定一致
     * 
     * DES加密的私钥,必须是8位长的字符串
     */
 
    private static final byte[] DESkey = Base64.decode("VW1nT3R2WVk=");// 设置密钥VW1nT3R2WVk=
    private static final byte[] DESIV = Base64.decode("WXlIeEhsY0o=");// 设置向量
    private static AlgorithmParameterSpec iv = null;// 加密算法的参数接口,IvParameterSpec是它的一个实现
    private static Key key = null;
 
    static {
        try {
            DESKeySpec keySpec = new DESKeySpec(DESkey);
            // 设置密钥参数
            iv = new IvParameterSpec(DESIV);// 设置向量
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");// 获得密钥工厂
            key = keyFactory.generateSecret(keySpec);// 得到密钥对象
            System.out.println(key.toString());
        } catch (InvalidKeyException e) {
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (InvalidKeySpecException e) {
            e.printStackTrace();
        }
    }
 
    public static String encode(String data) {
        String result = "";
        try {
            Cipher enCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");// 得到加密对象Cipher
            enCipher.init(Cipher.ENCRYPT_MODE, key, iv);// 设置工作模式为加密模式,给出密钥和向量
            byte[] pasByte = enCipher.doFinal(data.getBytes("utf-8"));
            result = Base64.encode(pasByte);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }
 
    public static String decode(String data) {
        String result = "";
        Cipher deCipher;
        try {
            deCipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            deCipher.init(Cipher.DECRYPT_MODE, key, iv);
            byte[] pasByte = deCipher.doFinal(Base64.decode(data));
            result = new String(pasByte, "UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
 
    }
}