下面代码片段通过 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 < buf.length; ++i) { String hex = Integer.toHexString(buf[i] & 255); if (hex.length() == 1) { hex = '0' + hex; } sb.append(hex.toUpperCase()); } return sb.toString(); } private static byte[] parseHexStr2Byte(String hexStr) { if (hexStr.length() < 1) { return null; } else { byte[] result = new byte[hexStr.length() / 2]; for (int i = 0; i < hexStr.length() / 2; ++i) { int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16); int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16); result[i] = (byte) (high * 16 + low); } return result; } } }
通过使用单元测试 JUnit 简单测试 DES 工具类的简单功能,代码如下:
import org.junit.jupiter.api.Test; /** * DesUtil 单元测试 * * @author hxstrive.com */ public class DesUtilTest { @Test public void demo() throws Exception { long temp = System.currentTimeMillis(); String message = "hello world"; System.out.println("原文:" + message + "\n"); temp = System.currentTimeMillis(); String messageEn = DesUtil.encrypt(message); System.out.println("密文:" + messageEn); System.out.println("加密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒\n"); temp = System.currentTimeMillis(); String messageDe = DesUtil.decrypt(messageEn); System.out.println("解密:" + messageDe); System.out.println("解密消耗时间:" + (System.currentTimeMillis() - temp) / 1000.0 + "秒"); } }
运行测试代码,输出如下:
原文:hello world 密文:53E35BFE7A4E6A458A7CABD9A629FFFF 加密消耗时间:0.874秒 解密:hello world 解密消耗时间:0.0秒