package com.jiyang.common.utils;
import com.jiyang.common.exception.ServiceException;
import org.apache.commons.codec.binary.Base64;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESedeKeySpec;
import javax.crypto.spec.IvParameterSpec;
import java.nio.charset.StandardCharsets;
import java.security.Key;
/**
* 3DES加解密工具类
*
*/
public class Des3Utils {
/**
* 加密算法
*/
private static final String KEY_ALGORITHM = "DESede";
private static final String CIPHER_ALGORITHM = "DESede/CBC/PKCS5Padding";
private static final String KEY = "PWNIOONCPPERMGEKYQQEOUEK";
private static final String IV = "12345678";
/**
* 3DES 加密
*
* @param key 秘钥(24位)
* @param iv 偏移量
* @param data 需要加密的字符串
* @return 返回加密的字符串
*/
public static String encrypt(String key, String iv, String data) {
try {
DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory secretKeyFactory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
Key dusky = secretKeyFactory.generateSecret(spec);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ips = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.ENCRYPT_MODE, dusky, ips);
byte[] bOut = cipher.doFinal(data.getBytes(StandardCharsets.UTF_8));
return Base64.encodeBase64String(bOut);
} catch (Exception e) {
throw new RuntimeException("3DES 解密错误, " + e.getMessage());
}
}
/**
* 3DES 解密
*
* @param key 秘钥(24位)
* @param iv 偏移量
* @param data 需要解密的密文
* @return 返回加密的字符串
*/
public static String decrypt(String key, String iv, String data) {
try {
DESedeKeySpec spec = new DESedeKeySpec(key.getBytes(StandardCharsets.UTF_8));
SecretKeyFactory factory = SecretKeyFactory.getInstance(KEY_ALGORITHM);
Key desk = factory.generateSecret(spec);
Cipher cipher = Cipher.getInstance(CIPHER_ALGORITHM);
IvParameterSpec ips = new IvParameterSpec(iv.getBytes(StandardCharsets.UTF_8));
cipher.init(Cipher.DECRYPT_MODE, desk, ips);
byte[] bOut = cipher.doFinal(Base64.decodeBase64(data.getBytes(StandardCharsets.UTF_8)));
return new String(bOut, StandardCharsets.UTF_8);
} catch (Exception e) {
throw new ServiceException("3DES 解密错误, " + e.getMessage());
}
}
/**
* 数据加密
*
* @param data 明文
* @return 加密字符串
*/
public static String encrypt(String data) {
return encrypt(KEY, IV, data);
}
/**
* 数据解密
*
* @param data 加密字符串
* @return 明文
*/
public static String decrypt(String data) {
return decrypt(KEY, IV, data);
}
public static void main(String[] args) {
String data = "123";
System.out.println("需要加密的字符串内容为:" + data);
String des3EncodeCBC = encrypt(data);
System.out.println("加密后的字符串内容为:" + des3EncodeCBC);
System.out.println("密文长度:" + des3EncodeCBC.length());
String des3DecodeCBC = decrypt(des3EncodeCBC + 123123);
System.out.println("解密后的字符串内容为:" + des3DecodeCBC);
}
}
评论