java 3DES (DESede/ECB/PKCS5Padding) 加解密

 代码如下:


import cn.hutool.core.convert.Convert;
import org.apache.commons.lang3.RandomStringUtils;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.Charset;

public class Util {

    private static final String key = RandomStringUtils.randomAlphanumeric(24);

    /**
     * 3DES加密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String encrypt3DES(String data) throws Exception {
        //加密
        byte key_byte[] = key.getBytes();
        SecretKey secretKey = new SecretKeySpec(key_byte, "DESede");
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(data.getBytes("utf-8"));
        String str = Convert.toHex(bytes);

        return str;
    }

    /**
     * 3DES解密
     *
     * @param data
     * @return
     * @throws Exception
     */
    public static String decrypt3DES(String data) throws Exception {
        //解密
        byte key_byte[] = key.getBytes();
        SecretKey secretKey = new SecretKeySpec(key_byte, "DESede");
        Cipher cipher = Cipher.getInstance("DESede/ECB/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, secretKey);
        byte[] bytes = cipher.doFinal(Convert.hexToBytes(data));
        String hex = Convert.toHex(bytes);
        String str = Convert.hexToStr(hex, Charset.forName("utf-8"));

        return str;
    }

    public static void main(String[] args) throws Exception {
        String str = "加解密测试!";
        System.out.println("随机key-----------> " + key);
        String encrypt3DES = encrypt3DES(str);
        System.out.println("加密-----------> " + encrypt3DES);
        String decrypt3DES = decrypt3DES(encrypt3DES);
        System.out.println("解密-----------> " + decrypt3DES);
    }
}

运行结果:

随机key-----------> vSEBYEGpBjfTseGyoaiVmUA1
加密-----------> 758d54430aec8c80b1f75b223dd8cd452639f1f1c9464440
解密-----------> 加解密测试!

ps:转载请注明出处

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值