1、基于des 的加密解密算法。
package com.redxun.eip.util;
import com.alibaba.fastjson.JSONObject;
import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.SecureRandom;
import java.util.Base64;
/**
* @Author hw
* @Date 2024/1/19 16:01
* @PackageName:com.redxun.eip.util
* @ClassName: DESUtils
* @Description: 请求DES 加密解密工具类
* @Version 1.0
*/
public class DESUtils {
private static final String DES = "DES";
private static final String key = "eip_interface_key_996";
/**
* 解密
*
* @param encryptedData 加密的String
* @param key 工号
* @return
* @throws Exception
*/
public static byte[] decrypt(byte[] encryptedData, String key) throws Exception {
SecureRandom random = new SecureRandom();
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.DECRYPT_MODE, secretKey, random);
return cipher.doFinal(encryptedData);
}
/**
* 使用 DES 密钥进行加密
*
* @param data 工号 公司
* @param key
* @return
* @throws Exception
*/
public static byte[] encrypt(byte[] data, String key) throws Exception {
SecureRandom random = new SecureRandom();
DESKeySpec desKeySpec = new DESKeySpec(key.getBytes("UTF-8"));
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(DES);
SecretKey secretKey = keyFactory.generateSecret(desKeySpec);
Cipher cipher = Cipher.getInstance(DES);
cipher.init(Cipher.ENCRYPT_MODE, secretKey, random);
return cipher.doFinal(data);
}
/**
* 解密的步骤
*
* @param data
*/
public static void decode(String data)throws Exception{
//先进行base64解码
byte[] encodedString = Base64.getDecoder().decode(data);
//再进行des解密
Object decryptedBytes = decrypt(encodedString, key);
String originalString = new String((byte[])decryptedBytes, "UTF-8");
System.out.println("解密后"+originalString);
}
/**
* 加密的步骤:
* 获取当前用户的工号、公司
*
* @return
* @throws Exception
*/
public static String encode(String userId,String companyId) throws Exception {
// 待加密的字符串
JSONObject object = new JSONObject();
object.put("userCode", userId);
object.put("companyCode", companyId);
String originalString = object.toJSONString();
System.out.println("加密前:"+originalString);
// 转换为字节数组
byte[] plaintextBytes = originalString.getBytes("UTF-8");
// 1、先使用DES密钥进行加密
byte[] encryptedBytes = encrypt(plaintextBytes, key);
// 2、再使用Base64进行编码
String encodedString = Base64.getEncoder().encodeToString(encryptedBytes);
return encodedString;
}
public static void main(String[] args) throws Exception {
// 加密
String endcodeStr = encode("0084710","C1300");
System.out.println("加密后:"+endcodeStr);
//解密
decode("JlZXELu/jttnx4lb6oUR+MU2usFp2z+FSK4ni/8VKOeEZkDS98QtMw==");
}
}