欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

DES加密 解密算法 / DES加密 解密工具类

程序员文章站 2022-03-12 19:08:48
...
package com.miku.qx.control;//改为自己的包路径

import java.io.IOException;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import org.apache.commons.codec.binary.Base64;

import sun.misc.BASE64Decoder;

/**
 * DES加密 解密算法
 *
 * @author lifq
 * @date 2015-3-17 上午10:12:11
 */
public class DESUtil {

    /**
     * Description 根据键值进行解密
     *
     * @param data
     *            加密键byte数组
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String decrypt(String data, String secretKey) throws IOException,
            Exception {
        if (data == null)
            return null;
        DESedeKeySpec keySpec = new DESedeKeySpec(secretKey.getBytes("UTF-8"));
        SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
        //获取解密对象
        Cipher cipher = Cipher.getInstance("DESede");
        //初始化解密信息
        cipher.init(Cipher.DECRYPT_MODE, key);
        //基于BASE64编码,接收byte[] 并转换成String
        BASE64Decoder base64decoder = new BASE64Decoder();
        //将字符串decode成byte[]
        byte[] bytes = base64decoder.decodeBuffer(data);
        //解密
        byte[] doFinal = cipher.doFinal(bytes);
        //返回解密之后的信息
        String jm= new String(doFinal, "UTF-8");
        System.out.println("DESUtil.decrypt--data:"+data+"----jm:"+jm);
        return jm;
    }

    /**
     * 加密
     * @param data
     * @param secretKey
     * @return
     * @throws IOException
     * @throws Exception
     */
    public static String encrypt(String data, String secretKey) throws IOException,
            Exception {
        if (data == null)
            return null;
        DESedeKeySpec keySpec = new DESedeKeySpec(secretKey.getBytes("UTF-8"));
        SecretKey key = SecretKeyFactory.getInstance("DESede").generateSecret(keySpec);
        Cipher cipher = Cipher.getInstance("DESede");
        cipher.init(Cipher.ENCRYPT_MODE, key);
        long timestr = System.currentTimeMillis();
        String temp = data+"-"+ timestr;

        byte[] utfData = temp.getBytes("UTF-8");
        byte[] encryptedText = cipher.doFinal(utfData);
        String token = new String(Base64.encodeBase64(encryptedText));
        System.out.println("DESUtil.encrypt--data:"+data+"----token:"+token);
        return token;
    }

}