Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android DES 對稱加密實作與注意事項

編輯:Android 程式設計入門

前言

端午前有同事來問 Android 上 DES 加密怎麼做,簡單實作了一下,順手整理成筆記。

DES 加密介紹

DES(Data Encryption Standard)是一種對稱加密演算法——加密與解密使用同一把金鑰。它出自 IBM 的研究,後來被美國政府正式採用,隨之廣泛流傳。

但近些年使用越來越少,原因很直接:DES 的有效金鑰只有 56 位,以現代的計算能力,24 小時內即可被破解。它今天主要存在於「對接老系統」的相容性場景裡。

DesUtil 常量定義

private final static String HEX = "0123456789ABCDEF";
// DES 是加密方式,CBC 是工作模式,PKCS5Padding 是填充模式
private final static String TRANSFORMATION = "DES/CBC/PKCS5Padding";
// 初始化向量,AES 為 16 bytes,DES 為 8 bytes
private final static String IVPARAMETERSPEC = "01020304";
private final static String ALGORITHM = "DES";
// SHA1PRNG 強隨機種子演算法,注意 4.2 以上版本的呼叫方式有差異
private static final String SHA1PRNG = "SHA1PRNG";

這幾個常數裡最值得注意的是 TRANSFORMATION 的字串格式:演算法/模式/填充。只寫 "DES" 的話,不同 JDK 供應商會採用不同預設值,導致跨平台解密失敗。顯式寫全是最保險的做法。

動態生成金鑰

金鑰長度不能小於 8 位元組,因為 DES 的固定格式是 64 bits,即 8 bytes。

/*
 * 生成隨機數作為動態金鑰。
 * 加密與解密必須使用同一把金鑰,否則無法解密。
 */
public static String generateKey() {
    try {
        SecureRandom localSecureRandom = SecureRandom.getInstance(SHA1PRNG);
        byte[] bytes_key = new byte[20];
        localSecureRandom.nextBytes(bytes_key);
        return toHex(bytes_key);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

// 位元組陣列轉十六進位字串
public static String toHex(byte[] buf) {
    if (buf == null) return "";
    StringBuffer result = new StringBuffer(2 * buf.length);
    for (int i = 0; i < buf.length; i++) {
        appendHex(result, buf[i]);
    }
    return result.toString();
}

private static void appendHex(StringBuffer sb, byte b) {
    sb.append(HEX.charAt((b >> 4) & 0x0f)).append(HEX.charAt(b & 0x0f));
}

處理金鑰的兩種方式

方式一:用 KeyGenerator 加種子

// 對金鑰進行處理
private static Key getRawKey(String key) throws Exception {
    KeyGenerator kgen = KeyGenerator.getInstance(ALGORITHM);
    SecureRandom sr;
    // Android 4.2 以上版本,SecureRandom 的取得方式發生了改變
    if (android.os.Build.VERSION.SDK_INT >= 17) {
        sr = SecureRandom.getInstance(SHA1PRNG, "Crypto");
    } else {
        sr = SecureRandom.getInstance(SHA1PRNG);
    }
    sr.setSeed(key.getBytes());
    kgen.init(64, sr);   // DES 固定 64 bits
    SecretKey skey = kgen.generateKey();
    byte[] raw = skey.getEncoded();
    return new SecretKeySpec(raw, ALGORITHM);
}

方式二:直接用 DESKeySpec

// 對金鑰進行處理
private static Key getRawKey(String key) throws Exception {
    DESKeySpec dks = new DESKeySpec(key.getBytes());
    SecretKeyFactory keyFactory = SecretKeyFactory.getInstance(ALGORITHM);
    return keyFactory.generateSecret(dks);
}

兩者差異在於:方式一透過 SHA1PRNG 把任意長度的字串「揉」成金鑰,方式二則直接取字串的位元組。方式二比較直覺,但要注意 DESKeySpec 只會取前 8 個位元組,餘下部分被忽略。

加密實作

/**
 * DES 加密
 * @param data 待加密字串
 * @param key  加密私鑰,長度不能小於 8 位
 * @return 加密後的結果,一般以 Base64 編碼後使用
 */
public static String encode(String key, String data) {
    return encode(key, data.getBytes());
}

/**
 * DES 加密
 * @param data 待加密位元組
 * @param key  加密私鑰
 * @return Base64 編碼後的密文
 */
public static String encode(String key, byte[] data) {
    try {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC.getBytes());
        cipher.init(Cipher.ENCRYPT_MODE, getRawKey(key), iv);
        byte[] bytes = cipher.doFinal(data);
        return Base64.encodeToString(bytes, Base64.DEFAULT);
    } catch (Exception e) {
        return null;
    }
}

解密實作

/**
 * DES 解密
 * @param key  解密私鑰
 * @param data Base64 編碼的密文
 */
public static String decode(String key, String data) {
    return decode(key, Base64.decode(data, Base64.DEFAULT));
}

/**
 * DES 解密
 * @param data 待解密的位元組
 * @param key  解密私鑰
 */
public static String decode(String key, byte[] data) {
    try {
        Cipher cipher = Cipher.getInstance(TRANSFORMATION);
        IvParameterSpec iv = new IvParameterSpec(IVPARAMETERSPEC.getBytes());
        cipher.init(Cipher.DECRYPT_MODE, getRawKey(key), iv);
        byte[] original = cipher.doFinal(data);
        return new String(original);
    } catch (Exception e) {
        return null;
    }
}

知識擴展:3DES

3DES(Triple DES)是 DES 的一種變形模式,使用三條 64 位金鑰對資料進行三次加密。1999 年 NIST 將 3DES 指定為過渡期的加密標準,它與 AES 之間的橋樑。3DES 以 DES 為基本模組,透過組合分組方法設計出更安全的分組加密演算法。

DES 與 AES 的比較

被問到為什麼用 DES 時,我內心深處是抗拒的。單從名字看,AES(Advanced Encryption Standard,高級加密標準)聽起來就比 DES 安全——事實也確實如此。

AES 的出現本來就是為了取代 DES,它在三個面向都更好:

  • 安全性:金鑰長度可達 128 / 192 / 256 位,目前沒有可行的破解途徑。
  • 效率:在現代 CPU 上有硬體指令加速,比 DES 快得多。
  • 靈活性:區塊長度固定 128 位,模式選擇豐富(GCM 還能同時提供完整性驗證)。

所以結論很明確:對稱加密優先選 AES。 只有在你必須對接既有的老系統、而對方只認 DES 時,才不得不使用它。

幾個實作上的安全提醒

  • IV 不要寫死。 這份程式碼把 IV 固定成 "01020304",在教學範例裡可以,但正式環境應該每次加密都隨機產生 IV,並把 IV 一起存進密文(IV 不需要保密)。固定 IV 會讓相同明文每次加密都得到相同密文,容易被比對出規律。
  • ECB 模式請勿使用。 有些教學寫 "DES/ECB/PKCS5Padding",ECB 會讓相同明文區塊產生相同密文,安全性極差。
  • 金鑰不要硬編碼在 App 裡。 APK 是可以被反編譯的,寫死金鑰等於沒有加密。真正需要保護敏感資料時,應使用 Android Keystore 系統讓金鑰存在硬體中。
  • 加密不等於雜湊。 如果是存密碼,應該用加鹽的雜湊(bcrypt、scrypt、Argon2),而不是可逆的加密。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved