Java实现DES编码加解密 - 密钥为: Text

  1. 编写工具类

    public class DesPasswordUtil {
    
        public static final String WIFI_DES_KEY = "TmuhP9PD";
    
        /**
         * 生成密钥
         *
         * @return {@link String }
         * @throws Exception 例外
         */
        public static SecretKeySpec createKeyFromText(String keyStr) throws Exception {
            if (keyStr.length() != 8) {
                throw new IllegalArgumentException("密钥长度必须为8个字符");
            }
            byte[] keyBytes = new byte[8];
            for (int i = 0; i < 8; i++) {
                keyBytes[i] = (byte) keyStr.charAt(i);
            }
            return new SecretKeySpec(keyBytes, "DES");
        }
    
        /**
         * 加密
         *
         * @param data 数据
         * @param key  钥匙
         * @return {@link String }
         * @throws Exception 例外
         */
        public static String encrypt(String data, SecretKeySpec key) throws Exception {
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key);
            byte[] encryptedBytes = cipher.doFinal(data.getBytes("UTF-8"));
            return Base64.getEncoder().encodeToString(encryptedBytes);
        }
    
        public static String decrypt(String encryptedData, SecretKeySpec key) throws Exception {
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decodedBytes = Base64.getDecoder().decode(encryptedData);
            byte[] decryptedBytes = cipher.doFinal(decodedBytes);
            return new String(decryptedBytes, "UTF-8");
        }
    
    
  2. 测试用例

    public static void main(String[] args) {
        try {
            String key = DesPasswordUtil.WIFI_DES_KEY;
            System.out.println("生成的密钥:" + DesPasswordUtil.WIFI_DES_KEY);
    
            SecretKeySpec keySpec = DesPasswordUtil.createKeyFromText(key);
    
            String data = "qwe123456!";
            String encryptedData = DesPasswordUtil.encrypt(data, keySpec);
            System.out.println("加密后的数据:" + encryptedData);
    
            String decryptedData = DesPasswordUtil.decrypt(encryptedData, keySpec);
            System.out.println("解密后的数据:" + decryptedData);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
  3. 输出结果

    生成的密钥:TmuhP9PD
    加密后的数据:G/uUbLmmnTFL1S9oEUzsNw==
    解密后的数据:qwe123456!
    

posted on 2025-01-20 18:33  我非柠檬为何心酸  阅读(31)  评论(0)    收藏  举报

导航