当前位置: 首页 > 工具软件 > EDE > 使用案例 >

3DES(DESede、Triple-DES、DES-EDE) 加解密 JAVA

姬歌者
2023-12-01

对称加密(DES、3DES)、非对称加密(RSA、SHA1withRSA)
参考:
https://blog.csdn.net/sinat_16998945/article/details/94639023

3DES、DESede、Triple-DES、DES-EDE名称相互都是别名

一、java加解密代码

默认模式为:DESede/ECB/PKCS5Padding

package com.pd.shop.utils;

import org.apache.tomcat.util.codec.binary.Base64;
import javax.crypto.*;
import javax.crypto.spec.DESedeKeySpec;
import java.security.Key;
import java.security.NoSuchAlgorithmException;

public class DESedeUtils {
    /**
     * 默认 DESede/ECB/PKCS5Padding
     */
    private static final String Algorithm = "DESede/ECB/PKCS5Padding";

    private static final String DESede = "DESede";

    private final static String Encoding = "utf-8";

    /**
     * DESede 加密
     *
     * @param src 加密数据
     * @param key 密钥
     * @return
     */
    public static String Encrypt(String src, String key) {
        String ss = "";
        try {
            byte[] b = Base64.decodeBase64(key);
            DESedeKeySpec spec = new DESedeKeySpec(b);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DESede);
            Key secretKey = keyFactory.generateSecret(spec);
            Cipher c1 = Cipher.getInstance(Algorithm);
            c1.init(1, secretKey);
            b = c1.doFinal(src.getBytes());
            ss = Base64.encodeBase64String(b);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        } catch (NoSuchPaddingException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
        return ss;
    }

    /**
     * DESede 解密
     *
     * @param src   解密数据
     * @param key   密钥
     * @return
     */
    public static String Decrypt(String src, String key) {
        try {
            byte[] s = Base64.decodeBase64(src);
            byte[] b = Base64.decodeBase64(key);
            DESedeKeySpec spec = new DESedeKeySpec(b);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DESede);
            Key secretKey = keyFactory.generateSecret(spec);
            Cipher cipher = Cipher.getInstance(Algorithm);
            cipher.init(2, secretKey);
            byte[] decryptData = cipher.doFinal(s);
            return new String(decryptData, Encoding);
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
}

二·、加解密调用方法

String str = "001张三*";
String key = "5d48b92bfcccc1db9d3d965b32ead033";

//加密调用方法
String encryptStr = DESedeUtils.Encrypt(str,key);
//结果 encryptStr = "eAgalz8MjYceOOI5V77fgA=="


//解密调用方法
String decryptStr = DESedeUtils.Decrypt(encryptStr,key);
//结果 decryptStr = "001张三*"
 类似资料: