首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java DES 加密算法實現:文件加密與字符串加密完整工具類

     編輯:Java 相關知識

DES(Data Encryption Standard)是經典對稱加密算法,雖然密鑰長度較短(56 位),在高安全性場景已被 AES 取代,但在舊系統維護、輕量級數據混淆、教學演示中仍有應用。本文提供基於 JDK javax.crypto 的完整 DES 工具類,支持 CBC 模式、PKCS5Padding、文件與字符串雙模式加解密。

核心工具類

import javax.crypto.*;
import javax.crypto.spec.*;
import java.io.*;
import java.security.SecureRandom;

public class DesTool {
    // 密鑰:8 字節(DES 固定)
    private static final String DES_KEY = "asfsdfsdf";  
    // IV 向量:8 字節(CBC 模式必需)
    private static final String IV_PARAM = "afasdf";    

    /** 文件加密/解密 */
    public static String encryptOrDecryptFile(String filePath, String fileName, int mode) {
        InputStream is = null;
        OutputStream os = null;
        CipherInputStream cis = null;

        try {
            // 1. 構建密鑰
            DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
            SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
            SecretKey key = kf.generateSecret(dks);

            // 2. 初始化 Cipher
            IvParameterSpec iv = new IvParameterSpec(IV_PARAM.getBytes());
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(mode, key, iv, new SecureRandom());

            // 3. 文件流處理
            File inFile = new File(filePath, fileName);
            File outDir = new File(filePath, "encrypted");
            if (!outDir.exists()) outDir.mkdirs();
            File outFile = new File(outDir, fileName);

            is = new FileInputStream(inFile);
            os = new FileOutputStream(outFile);
            cis = new CipherInputStream(is, cipher);

            byte[] buffer = new byte[1024];
            int len;
            while ((len = cis.read(buffer)) > 0) {
                os.write(buffer, 0, len);
            }
            return outFile.getAbsolutePath();

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        } finally {
            closeQuietly(is, cis, os);
        }
    }

    /** 字符串加密/解密 */
    public static String encryptOrDecryptString(String src, int mode) {
        try {
            DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
            SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
            SecretKey key = kf.generateSecret(dks);

            IvParameterSpec iv = new IvParameterSpec(IV_PARAM.getBytes());
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(mode, key, iv, new SecureRandom());

            CipherInputStream cis = new CipherInputStream(
                new ByteArrayInputStream(src.getBytes()), cipher);
            ByteArrayOutputStream baos = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int len;
            while ((len = cis.read(buffer)) > 0) {
                baos.write(buffer, 0, len);
            }
            return baos.toString();  // 注意:解密後需指定編碼 new String(bytes, "UTF-8")

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    // 安全關閉資源
    private static void closeQuietly(Closeable... closeables) {
        for (Closeable c : closeables) {
            if (c != null) try { c.close(); } catch (IOException ignored) {}
        }
    }

    // 測試
    public static void main(String[] args) {
        String original = "敏感數據:用戶ID=10086";
        System.out.println("原文: " + original);

        String encrypted = encryptOrDecryptString(original, Cipher.ENCRYPT_MODE);
        System.out.println("加密: " + encrypted);  // 亂碼/二進制字符串

        String decrypted = encryptOrDecryptString(encrypted, Cipher.DECRYPT_MODE);
        System.out.println("解密: " + decrypted);
    }
}

關鍵參數詳解

參數值說明
算法/模式/填充DES/CBC/PKCS5PaddingCBC 模式需 IV,PKCS5 填充至 8 字節倍數
密鑰長度8 字節 (56 位有效)DES 固定,不足補齊,超出截取
IV 長度8 字節CBC 模式必需,建議隨機生成並隨密文傳輸
SecureRandom加密隨機源增強安全性

安全性警示與最佳實踐

  1. DES 已不安全:56 位密鑰可在數小時內暴力破解,生產環境請用 AES-256-GCM
  2. 硬編碼密鑰極危險:應從配置中心、密鑰管理系統(KMS)、環境變量獲取
  3. IV 應隨機生成:每次加密生成新 IV,與密文一起存儲(IV 不需保密)
  4. 字符串加密輸出:加密結果為二進制,傳輸/存儲時需 Base64 或 Hex 編碼
  5. 異常處理:捕獲 BadPaddingException、IllegalBlockSizeException 區分密鑰錯誤/數據損壞

AES 替代示例(推薦)

// 僅需修改算法名與密鑰長度
Cipher cipher = Cipher.getInstance("AES/GCM/NoPadding");  // 推薦 GCM 認證加密
SecretKeySpec keySpec = new SecretKeySpec(aesKeyBytes, "AES");  // 32 字節密鑰
GCMParameterSpec gcmSpec = new GCMParameterSpec(128, ivBytes);  // 12 字節 IV
cipher.init(mode, keySpec, gcmSpec);

理解 DES 算法結構、CBC 模式、填充機制、IV 作用,是掌握現代對稱加密(AES、ChaCha20)的基石。工程中請堅決遷移至 AES-GCM 或 ChaCha20-Poly1305。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved