下面代码片段通过 JDK 内置的 API 实现 DES 对称加密算法,提供静态方法 decrypt() 和 encrypt(),分别用于加密和解密字符串。 代码片段import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.security.spec.InvalidKeySpecException;
/**
* DES常用解密加密工具类
*
* @author hxstrive.com
*/
public class DesUtil {
/**
* 默认的字符编码
*/
private static final String DEFAULT_CHARSET = "UTF-8";
/**
* 秘钥字符串
*/
private static final String PASSWORD = "E6oQo-Tbqv^kVwQtT90sRJ9yQ534gXTvosRgm5$OWu8brv3ZE4PUHi-Ul%YisBrC";
/**
* 算法名称
*/
private static final String ALGORITHM = "DES";
private static SecretKey getSecretkey() throws InvalidKeyException, NoSuchAlgorithmException,
InvalidKeySpecException {
// 创建一个DESKeySpec对象,PASSWORD可任意指定
DESKeySpec desKey = new DESKeySpec(PASSWORD.getBytes());
// 创建一个密匙工厂
SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
// 生成密钥
return keyFactory.generateSecret(desKey);
}
/**
* 解密DES
*
* @param datasource 需要加密的内容
* @return 解密后的明文数据
*/
public static String decrypt(String datasource) {
try {
// 生成密钥
SecretKey secretkey = getSecretkey();
// 指定获取DES的Cipher对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
// 用密匙初始化Cipher对象
cipher.init(Cipher.DECRYPT_MODE, secretkey, new SecureRandom());
// 真正开始解密操作
return new String(cipher.doFinal(parseHexStr2Byte(datasource)));
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
/**
* 加密DES
*
* @param datasource 需要加密的内容
* @return 加密的内容
*/
public static String encrypt(String datasource) {
try {
SecretKey secretKey = getSecretkey();
//指定获取DES的Cipher对象
Cipher cipher = Cipher.getInstance(ALGORITHM);
//用密匙初始化Cipher对象
cipher.init(Cipher.ENCRYPT_MODE, secretKey, new SecureRandom());
//数据加密
return parseByte2HexStr(cipher.doFinal(datasource.getBytes(DEFAULT_CHARSET)));
} catch (Throwable e) {
e.printStackTrace();
}
return null;
}
public static String parseByte2HexStr(byte[] buf) {
StringBuffer sb = new StringBuffer();
for (int i = 0; i |