DES加密解密

package com.abc.util;

/**
 * DES加密 解密算法
 * Created by xxx.
 */

import org.apache.commons.codec.binary.Base64;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

public class YxDESUtil {
    private final String defaultKey = "85a9ad84";
    private final String charsetName = "utf-8";
    private static YxDESUtil instance = null;

    public YxDESUtil() {
    }

    public static YxDESUtil getInstance() {
        if (null == instance) {
            instance = new YxDESUtil();
        }

        return instance;
    }

    /*
    利用key进行加密,key长度必须=8
     */
    public String encode(String data, String key) {
        String res = "";

        try {
            // 根据给定的字节数组构建一个秘钥
            byte[] raw = key.getBytes(charsetName);
            SecretKeySpec sc = new SecretKeySpec(raw, "DES");

            // 加密
            // 1.获取加密算法工具类
            Cipher cipher = Cipher.getInstance("DES");

            // 2.对工具类对象进行初始化,
            // mode:加密/解密模式
            // key:对原始秘钥处理之后的秘钥
            cipher.init(Cipher.ENCRYPT_MODE, sc);

            // 3.用加密工具类对象对明文进行加密
            byte[] encipherByte = cipher.doFinal(data.getBytes(charsetName));

            // 防止乱码,使用Base64编码
            res = Base64.encodeBase64String(encipherByte);
        } catch (Exception e) {
            ///
        }

        return res;
    }

    /*
    利用key进行解密,key长度必须=8
     */
    public String decode(String data, String key) {
        String res = "";

        try {
            // 根据给定的字节数组构建一个秘钥
            byte[] raw = key.getBytes(charsetName);
            SecretKeySpec sc = new SecretKeySpec(raw, "DES");

            // 加密
            // 1.获取加密算法工具类
            Cipher cipher = Cipher.getInstance("DES");

            // 解密
            // 2.对工具类对象进行初始化
            cipher.init(Cipher.DECRYPT_MODE, sc);

            // 3.用加密工具类对象对密文进行解密
            byte[] decode = Base64.decodeBase64(data);
            byte[] decipherByte = cipher.doFinal(decode);
            res = new String(decipherByte, charsetName);
        } catch (Exception e) {
            ////
        }

        return res;
    }

    /*
    使用默认密码进行加密
     */
    public String encode(String data) {
        return encode(data, this.defaultKey);
    }

    /*
    使用默认密码进行解密
     */
    public String decode(String data) {
        return decode(data, this.defaultKey);
    }
}

 

posted @ 2020-11-17 11:19  都是城市惹的祸  阅读(53)  评论(0)    收藏  举报