01_DES加密算法

/**
 * <p>Description: DES 算法加密</p>
 *
 * @author XXX
 * @date 2020/11/25 21:56
 * @since JDK1.8
 */
public class DESEncryption {
    private static Base64.Encoder encoder = Base64.getEncoder();
    private static Base64.Decoder decoder = Base64.getDecoder();

    private static String desEncrypt(String text, String originKey) throws Exception {

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

        //对原始秘钥处理后的秘钥
        SecretKeySpec key = getKey(originKey);
        cipher.init(Cipher.ENCRYPT_MODE, key);

        //用加密算法对明文进行加密
        byte[] bytes = cipher.doFinal(text.getBytes());

        return new String(encoder.encode(bytes));
    }

    private static String desDecrypt(String encrypt, String originKey) throws Exception {

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

        //对原始秘钥处理后的秘钥
        SecretKeySpec key = getKey(originKey);
        cipher.init(Cipher.DECRYPT_MODE, key);

        //用加密算法对明文进行加密
        byte[] bytes = cipher.doFinal(decoder.decode(encrypt.getBytes()));

        return new String(bytes);
    }


    private static SecretKeySpec getKey(String originKey) {

        //DES 算法要求为64位,8个字节
        byte[] buffer = new byte[8];

        byte[] bytes = originKey.getBytes();

        for (int i = 0; i < 8 && i < bytes.length; i++) {
            buffer[i] = bytes[i];
        }

        //根据原始秘钥构造一个新的秘钥,要求 buffer.length = 8
        return new SecretKeySpec(buffer, "DES");
    }


    public static void main(String[] args) throws Exception {

        String originKey = "ADE43SWIM21";

        String text = "hello";
        System.out.println("加密前:" + text);

        String encrypt = desEncrypt(text, originKey);
        System.out.println("加密后:" + encrypt);

        String decrypt = desDecrypt(encrypt, originKey);
        System.out.println("解密后:" + decrypt);
    }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值