Java实现DES编码加解密 - 密钥为: Hex
-
编写工具类
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
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 分享4款.NET开源、免费、实用的商城系统
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· 记一次.NET内存居高不下排查解决与启示