简单des加密解密工具类(自定义密钥)

package com.test.common.utils;

import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;

/**
 * des加密解密工具类
 */
public class DESUtils {


    /**
     * des加密
     * @param keyString 自定义密钥字符串
     * @param data 需要加密的参数
     * @return
     * @throws Exception
     */
    public static String encryptBaseDes(String keyString, String data) throws Exception {

        //将自定义密钥转为字节型
        byte[] encryptKey = keyString.getBytes();

        String encryptedData  = null;
        //DES算法要求一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        DESKeySpec deskey = new DESKeySpec(encryptKey);

        //创建一个密钥工厂,然后用它把DESKeySpec转换成一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(deskey);

        //加密对象
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.ENCRYPT_MODE, key, sr);

        //加密,把字节数组编码成字符串
        encryptedData = new BASE64Encoder().encode(cipher.doFinal(data.getBytes()));

        return encryptedData;
    }


    /**
     * 解密字符串
     * @param keyString 自定义密钥字符串
     * @param desData 需要解密的参数
     * @return
     * @throws Exception
     */
    public static String decryptBaseDes(String keyString, String desData) throws Exception {

        //将自定义密钥转为字节型
        byte[] encryptKey = keyString.getBytes();

        String decryptedData = null;

        //DES算法要求有一个可信任的随机数源
        SecureRandom sr = new SecureRandom();
        DESKeySpec desKey = new DESKeySpec(encryptKey);

        //创建一个密钥工厂,把DESKeySpec转换成一个SecretKey对象
        SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
        SecretKey key = keyFactory.generateSecret(desKey);

        //解密对象
        Cipher cipher = Cipher.getInstance("DES");
        cipher.init(Cipher.DECRYPT_MODE, key, sr);

        //字符串解码 ——> 字节数组,并解密
        decryptedData = new String(cipher.doFinal(new BASE64Decoder().decodeBuffer(desData)));
        return decryptedData;
    }
}

参考博客:
java使用DES对密码进行加密和解密源代码

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值