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

Android DES 加密:CBC 模式與 ECB 模式加解密實作

編輯:關於 Android 程式設計

DES 加密共有四種工作模式:電子密碼本模式(ECB)、加密分組鏈接模式(CBC)、加密回饋模式(CFB)與輸出回饋模式(OFB)。本文聚焦在最常用的 CBC 與 ECB 兩種,並提供可直接套用的加解密工具類。

CBC 模式加密

CBC 模式在加密時需要額外傳入一個初始向量(IV),讓相同的明文在每次加密時都能產生不同的密文,安全性優於 ECB。

import java.security.Key;
import java.security.spec.AlgorithmParameterSpec;
import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import javax.crypto.spec.IvParameterSpec;
import com.sun.org.apache.xml.internal.security.utils.Base64;

public class DesCbcUtil {
    public static final String ALGORITHM_DES = "DES/CBC/PKCS5Padding";

    /** 加密(傳入字串) */
    public static String encode(String key, String data) throws Exception {
        return encode(key, data.getBytes());
    }

    /** 加密(傳入位元組) */
    public static String encode(String key, byte[] data) throws Exception {
        try {
            byte[] ivbyte = { 1, 2, 3, 4, 5, 6, 7, 8 };
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            // key 的長度不能夠小於 8 位字節
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec(ivbyte);
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.ENCRYPT_MODE, secretKey, paramSpec);

            byte[] bytes = cipher.doFinal(data);
            return Base64.encode(bytes);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /** 解密 */
    public static byte[] decode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            IvParameterSpec iv = new IvParameterSpec("12345678".getBytes());
            AlgorithmParameterSpec paramSpec = iv;
            cipher.init(Cipher.DECRYPT_MODE, secretKey, paramSpec);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /** 取得解密後的值 */
    public static String decodeValue(String key, String data) {
        byte[] datas;
        String value = null;
        try {
            datas = decode(key, Base64.decode(data));
            value = new String(datas);
        } catch (Exception e) {
            value = "";
        }
        return value;
    }
}

ECB 模式加密

ECB 模式不需要 IV,相同明文會產生相同密文,實作最簡單,但安全性相對較低,適合對安全要求不高的場景。

import javax.crypto.Cipher;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;
import android.util.Base64;

public class DesEcbUtil {
    public static final String ALGORITHM_DES = "DES/ECB/PKCS5Padding";

    /** 加密(傳入字串) */
    public static String encode(String key, String data) throws Exception {
        return encode(key, data.getBytes());
    }

    /** 加密(傳入位元組) */
    public static String encode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);

            byte[] bytes = cipher.doFinal(data);
            return Base64.encodeToString(bytes, 3);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /** 解密 */
    public static byte[] decode(String key, byte[] data) throws Exception {
        try {
            DESKeySpec dks = new DESKeySpec(key.getBytes());
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            Key secretKey = keyFactory.generateSecret(dks);
            Cipher cipher = Cipher.getInstance(ALGORITHM_DES);
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            return cipher.doFinal(data);
        } catch (Exception e) {
            throw new Exception(e);
        }
    }

    /** 取得解密後的值 */
    public static String decodeValue(String key, String data) {
        byte[] datas;
        String value = null;
        try {
            datas = decode(key, Base64.decode(data, 3));
            value = new String(datas);
        } catch (Exception e) {
            value = "";
        }
        return value;
    }
}

測試範例

CBC 模式的測試方式與 ECB 完全相同,這裡以 ECB 為例:

try {
    // 待加密內容
    String str = "";
    String pwdKey = "moshapp";
    String pwdKeyMD5 = MD5Util.encode(pwdKey);
    System.out.println("pwdKeyMD5:" + pwdKeyMD5);

    String encodeStr = DesEcbUtil.encode(pwdKeyMD5, str);
    String decodeStr = DesEcbUtil.decodeValue(pwdKeyMD5, encodeStr);
    System.out.println("加密前的字符串:" + str);
    System.out.println("加密後的字符串:" + encodeStr);
    System.out.println("解密後的字符串:" + decodeStr);

    // URL 轉義
    final String encodedURL = URLEncoder.encode(encodeStr, "UTF-8");
    System.out.println("轉義後的字符串:" + encodedURL);
} catch (Exception e) {
    e.printStackTrace();
}

實務上,若密文要放進 URL 傳輸,記得先做 URL 編碼;解密端則先解碼再還原。此外提醒一句,DES 的密钥長度受限(實作中通常取前 8 位元組),在對安全性有較高要求的專案中,建議改用 AES 等更現代的加密演算法。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved