Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android AES 加密工具類完整實作(PKCS5Padding)

編輯:Android 開發實例

Java 環境不支援 PKCS7Padding,只支援 PKCS5Padding。由於對稱加密的組成是「演算法 + 模式 + 填充」,這裡就採用 AES/ECB/PKCS5Padding 的組合實作一支可直接複用的工具類別。實務上 AES 的填充在兩者之間是相容的,因此這支類別也能與 iOS 端互通。

工具類別原始碼

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;
    }

    /** 加密字串,結果為十六進位字串 */
    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;
    }

    /** 將十六進位字串解密回原字串 */
    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;
    }

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

    /** 十六進位字串轉位元組陣列 */
    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();
        }
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}

實際輸出

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

安全性提醒

這支類別示範的是最基礎的用法,直接上 production 之前有幾點必須改善。ECB 模式不安全:它對每個區塊獨立加密,相同明文會產生相同密文,能從密文推論出明文的重複結構(這就是著名的「ECB 企鵝圖」問題),正式環境應改用 CBC 或 GCM 模式並搭配隨機 IV。金鑰不應由補零產生:範例把密碼補到 32 位元組當金鑰,熵值遠低於真正的 256 位金鑰,實務上應改用 PBKDF2 或 scrypt 之類的金鑰衍生函式,並加入隨機 salt。

此外,金鑰若需要跨裝置保存,請交給 Android Keystore 系統管理,而不是硬寫在程式碼或 SharedPreferences 裡。

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