-
编写工具类
public class DesPasswordUtil { public static final String WIFI_DES_KEY = "TmuhP9PDtcQ="; /** * 生成密钥 * * @return {@link String } * @throws Exception 例外 */ public static String generateKey() throws Exception { KeyGenerator keyGenerator = KeyGenerator.getInstance("DES"); keyGenerator.init(56); // DES密钥长度为56位 SecretKey secretKey = keyGenerator.generateKey(); byte[] keyBytes = secretKey.getEncoded(); // 截取前8字节 byte[] truncatedKeyBytes = new byte[8]; System.arraycopy(keyBytes, 0, truncatedKeyBytes, 0, 8); return Base64.getEncoder().encodeToString(truncatedKeyBytes); } /** * 加密 * * @param data 数据 * @param key 钥匙 * @return {@link String } * @throws Exception 例外 */ public static String encrypt(String data, String key) throws Exception { byte[] keyBytes = Base64.getDecoder().decode(key); // 确保密钥长度为8字节 if (keyBytes.length != 8) { throw new IllegalArgumentException("密钥长度必须为8字节"); } SecretKey secretKey = new SecretKeySpec(keyBytes, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.ENCRYPT_MODE, secretKey); byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8")); return Base64.getEncoder().encodeToString(encryptedBytes); } /** * 解密 * * @param encryptedData 加密数据 * @param key 钥匙 * @return {@link String } * @throws Exception 例外 */ public static String decrypt(String encryptedData, String key) throws Exception { byte[] encryptedBytes = Base64.getDecoder().decode(encryptedData); byte[] keyBytes = Base64.getDecoder().decode(key); // 确保密钥长度为8字节 if (keyBytes.length != 8) { throw new IllegalArgumentException("密钥长度必须为8字节"); } SecretKey secretKey = new SecretKeySpec(keyBytes, "DES"); Cipher cipher = Cipher.getInstance("DES"); cipher.init(Cipher.DECRYPT_MODE, secretKey); byte[] decryptedBytes = cipher.doFinal(encryptedBytes); return new String(decryptedBytes, "UTF-8"); } }
-
测试用例
public static void main(String[] args) { try { String key = "H1eP+wGDMW0="; System.out.println("生成的密钥:" + key); String data = "123456"; String encryptedData = DesPasswordUtil.encrypt(data, key); System.out.println("加密后的数据:" + encryptedData); String decryptedData = DesPasswordUtil.decrypt(encryptedData, key); System.out.println("解密后的数据:" + decryptedData); } catch (Exception e) { e.printStackTrace(); } } }
-
输出结果
生成的密钥:H1eP+wGDMW0= 加密后的数据:hrKE2n/Pj0E= 解密后的数据:123456