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

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

程序员文章站 2024-03-14 11:10:40
...

 代码如下:


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:转载请注明出处

相关标签: java java