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

Android AES 對稱加密工具類分享

編輯:關於 Android 程式設計

AES 是最常用的對稱式加密演算法。本文提供一個可直接複用的 Android AES 加解密工具類,並說明加密字串組成的觀念。

加密的三個組成部分

一個完整的加密方案由「演算法 + 模式 + 填充」組成。Java 不支援 PKCS7Padding,只支援 PKCS5Padding,因此本文使用 AES/ECB/PKCS5Padding。
要注意 ECB 模式相同明文會產生相同密文,安全性較弱,正式專案建議改用 AES/CBC/PKCS5Padding 並搭配隨機 IV;若要做跨 iOS 與 Android 通用的方案,雙方的模式與填充必須完全一致。

一、AESHelper 工具類

package com.example.aesdemo;

import java.io.UnsupportedEncodingException;
import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;

/** AES 對稱加密解密類 **/
public class AESHelper {
    /** 演算法/模式/填充 **/
    private static final String CipherMode = "AES/ECB/PKCS5Padding";

    /** 建立金鑰:不足 32 位元補 0,超出則截斷 **/
    private static SecretKeySpec createKey(String password) {
        byte[] data = null;
        if (password == null) {
            password = "";
        }
        StringBuffer sb = new StringBuffer(32);
        sb.append(password);
        while (sb.length() < 32) {
            sb.append("0");
        }
        if (sb.length() > 32) {
            sb.setLength(32);
        }
        try {
            data = sb.toString().getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return new SecretKeySpec(data, "AES");
    }

    /** 加密位元組資料 **/
    public static byte[] encrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 加密(結果為 16 進位字串) **/
    public static String encrypt(String content, String password) {
        byte[] data = null;
        try {
            data = content.getBytes("UTF-8");
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = encrypt(data, password);
        return byte2hex(data);
    }

    /** 解密位元組陣列 **/
    public static byte[] decrypt(byte[] content, String password) {
        try {
            SecretKeySpec key = createKey(password);
            Cipher cipher = Cipher.getInstance(CipherMode);
            cipher.init(Cipher.DECRYPT_MODE, key);
            return cipher.doFinal(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 將 16 進位字串解密為字串 **/
    public static String decrypt(String content, String password) {
        byte[] data = null;
        try {
            data = hex2byte(content);
        } catch (Exception e) {
            e.printStackTrace();
        }
        data = decrypt(data, password);
        if (data == null) return null;
        try {
            return new String(data, "UTF-8");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 位元組陣列轉 16 進位字串 **/
    public static String byte2hex(byte[] b) {
        StringBuffer sb = new StringBuffer(b.length * 2);
        String tmp = "";
        for (int n = 0; n < b.length; n++) {
            tmp = (java.lang.Integer.toHexString(b[n] & 0XFF));
            if (tmp.length() == 1) {
                sb.append("0");
            }
            sb.append(tmp);
        }
        return sb.toString().toUpperCase();
    }

    /** 將 hex 字串轉換成位元組陣列 **/
    private static byte[] hex2byte(String inputString) {
        if (inputString == null || inputString.length() < 2) {
            return new byte[0];
        }
        inputString = inputString.toLowerCase();
        int l = inputString.length() / 2;
        byte[] result = new byte[l];
        for (int i = 0; i < l; ++i) {
            String tmp = inputString.substring(2 * i, 2 * i + 2);
            result[i] = (byte) (Integer.parseInt(tmp, 16) & 0xFF);
        }
        return result;
    }
}

二、使用方式

public class MainActivity extends Activity {
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        String masterPassword = "a";
        String originalText = "於";
        try {
            String encryptingCode = AESHelper.encrypt(originalText, masterPassword);
            Log.i("加密結果為 ", encryptingCode);
            String decryptingCode = AESHelper.decrypt(encryptingCode, masterPassword);
            Log.i("解密結果", decryptingCode);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

三、執行結果

09-19 10:41:05.467: I/加密結果為(707): E55C24701F6380478E1940ADDFD08D22
09-19 10:41:05.467: I/解密結果(707): 於

安全提醒

這個類別把金鑰直接由密碼字串補零而來,方便示範但不適合正式環境:金鑰若硬編碼在 APK 中,反編譯後即可輕易取得。實務上應改用 Android Keystore 產生並保存金鑰,或以 PBKDF2 從使用者密碼衍生的金鑰,並搭配 CBC 模式與隨機 IV。另外,若加解密過程發生任何例外,doFinal 都會失敗,此時工具類回傳 null,呼叫端務必做 null 判斷,避免後續 byte2hex 收到 null 而拋出 NullPointerException。

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