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

Java DES 加密工具類:檔案與字串加解密完整實作(CBC/PKCS5Padding)

     編輯:Java 程式設計入門

演算法參數

  • 演算法:DES
  • 模式:CBC(密碼塊鏈接,需 IV)
  • 填充:PKCS5Padding
  • 金鑰長度:56 位(8 字節,含 8 位校驗位)
  • IV 長度:8 字節

核心工具類 DesTool

public class DesTool {
    private static final String PASS_KEY = "afasdf"; // IV
    private static final String DES_KEY  = "asfsdfsdf"; // Key

    /** 檔案加解密 */
    public static String encoderOrDecoder(String filePath, String fileName, int mode) {
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
            SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
            SecretKey key = kf.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec(PASS_KEY.getBytes());
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(mode, key, iv, sr);

            File inFile = new File(filePath, fileName);
            File outDir = new File(filePath, "encoder");
            outDir.mkdirs();
            File outFile = new File(outDir, fileName);

            try (FileInputStream fis = new FileInputStream(inFile);
                 FileOutputStream fos = new FileOutputStream(outFile);
                 CipherInputStream cis = new CipherInputStream(fis, cipher)) {
                byte[] buf = new byte[1024];
                int len;
                while ((len = cis.read(buf)) > 0) fos.write(buf, 0, len);
            }
            return outFile.getAbsolutePath();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    /** 字串加解密 */
    public static String encoderOrDecoder(String src, int mode) {
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec dks = new DESKeySpec(DES_KEY.getBytes());
            SecretKeyFactory kf = SecretKeyFactory.getInstance("DES");
            SecretKey key = kf.generateSecret(dks);
            IvParameterSpec iv = new IvParameterSpec(PASS_KEY.getBytes());
            Cipher cipher = Cipher.getInstance("DES/CBC/PKCS5Padding");
            cipher.init(mode, key, iv, sr);

            try (ByteArrayInputStream bis = new ByteArrayInputStream(src.getBytes("UTF-8"));
                 CipherInputStream cis = new CipherInputStream(bis, cipher);
                 ByteArrayOutputStream bos = new ByteArrayOutputStream()) {
                byte[] buf = new byte[1024];
                int len;
                while ((len = cis.read(buf)) > 0) bos.write(buf, 0, len);
                return bos.toString("UTF-8");
            }
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }

    public static void main(String[] args) throws Exception {
        String plain = "敏感資料測試";
        String enc = encoderOrDecoder(plain, Cipher.ENCRYPT_MODE);
        String dec = encoderOrDecoder(enc, Cipher.DECRYPT_MODE);
        System.out.println("原文: " + plain);
        System.out.println("密文: " + enc);
        System.out.println("解密: " + dec);
    }
}

關鍵安全提醒

AES-256 升級範例(推薦)

// 金鑰 32 字節,IV 16 字節
Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
SecretKeySpec keySpec = new SecretKeySpec(keyBytes, "AES");
IvParameterSpec ivSpec = new IvParameterSpec(ivBytes);
cipher.init(mode, keySpec, ivSpec);
// 其餘流程相同

Base64 編碼密文(便於傳輸/存儲)

// 加密後
String encBase64 = Base64.getEncoder().encodeToString(cipher.doFinal(plainBytes));
// 解密前
byte[] encBytes = Base64.getDecoder().decode(encBase64);
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved
風險說明建議
DES 強度不足56 位金鑰現代算力可暴力破解生產環境請用 AES-256
硬編碼金鑰/IV原始碼洩露即導致資料外洩金鑰放配置檔/環境變數/金鑰管理系統
固定 IVCBC 模式固定 IV 降低語義安全性每次加密生成隨機 IV,與密文一併存储
字串加密直接 toStringByteArrayOutputStream.toString() 依賴平台預設編碼明確指定 toString("UTF-8") 或 Base64 編碼輸出