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

Android 中的 AES 加解密實作:一個能真正跑通的工具類

編輯:關於 Android 程式設計

在專案裡加入 AES 加解密時,網路上找得到的範例多到嚇人,但真正能跑通的少得驚人。常見的失敗模式有兩種:一是加密字串在 Java 端解不開,二是同一份程式碼換到不同裝置結果就不一樣。這裡把實測可行的版本記錄下來,並說明關鍵在哪裡。

一、AES 工具類別

 package com.example.cheng.aesencrypt;

import android.text.TextUtils;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Aes {
    private static final String SHA1PRNG = "SHA1PRNG";   // 強隨機種子演算法
    private static final String IV = "qws871bz73msl9x8";
    private static final String AES = "AES";
    private static final String CIPHERMODE = "AES/CBC/PKCS5Padding";  // 演算法/模式/填充

    /** 加密,回傳十六進位字串 */
    public static String encrypt(String key, String cleartext) {
        if (TextUtils.isEmpty(cleartext)) {
            return cleartext;
        }
        try {
            byte[] result = encrypt(key, cleartext.getBytes());
            return parseByte2HexStr(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 加密,回傳位元組 */
    public static byte[] encrypt(String key, byte[] clear) throws Exception {
        byte[] raw = getRawKey(key.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(CIPHERMODE);
        cipher.init(Cipher.ENCRYPT_MODE, skeySpec,
                new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(clear);
    }

    /** 解密,輸入十六進位字串 */
    public static String decrypt(String key, String encrypted) {
        if (TextUtils.isEmpty(encrypted)) {
            return encrypted;
        }
        try {
            byte[] enc = parseHexStr2Byte(encrypted);
            byte[] result = decrypt(key, enc);
            return new String(result);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 解密,輸入位元組 */
    public static byte[] decrypt(String key, byte[] encrypted) throws Exception {
        byte[] raw = getRawKey(key.getBytes());
        SecretKeySpec skeySpec = new SecretKeySpec(raw, AES);
        Cipher cipher = Cipher.getInstance(CIPHERMODE);
        cipher.init(Cipher.DECRYPT_MODE, skeySpec,
                new IvParameterSpec(new byte[cipher.getBlockSize()]));
        return cipher.doFinal(encrypted);
    }

    /** 產生隨機金鑰,可作為動態金鑰;加解密雙方必須一致 */
    public static String generateKey() {
        try {
            SecureRandom secureRandom = SecureRandom.getInstance(SHA1PRNG);
            byte[] key = new byte[20];
            secureRandom.nextBytes(key);
            return toHex(key);
        } catch (NoSuchAlgorithmException e) {
            e.printStackTrace();
        }
        return null;
    }

    /** 處理金鑰 */
    public static byte[] getRawKey(byte[] seed) throws Exception {
        KeyGenerator kgen = KeyGenerator.getInstance(AES);
        SecureRandom sr = null;
        // 4.2 以上版本,SecureRandom 的取得方式有變
        if (android.os.Build.VERSION.SDK_INT >= 17) {
            sr = SecureRandom.getInstance(SHA1PRNG, "Crypto");
        } else {
            sr = SecureRandom.getInstance(SHA1PRNG);
        }
        sr.setSeed(seed);
        kgen.init(128, sr);
        // AES 的 128 位元金鑰有 10 輪加密,192 位元有 12 輪,256 位元有 14 輪
        SecretKey skey = kgen.generateKey();
        return skey.getEncoded();
    }

    /** 位元組轉十六進位字串 */
    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(IV.charAt((b >> 4) & 0x0f)).append(IV.charAt(b & 0x0f));
    }

    /** 位元組轉十六進位(大寫) */
    public static String parseByte2HexStr(byte buf[]) {
        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < buf.length; i++) {
            String hex = Integer.toHexString(buf[i] & 0xFF);
            if (hex.length() == 1) {
                hex = '0' + hex;
            }
            sb.append(hex.toUpperCase());
        }
        return sb.toString();
    }

    /** 十六進位字串轉位元組 */
    public static byte[] parseHexStr2Byte(String hexStr) {
        if (hexStr.length() < 1) return null;
        byte[] result = new byte[hexStr.length() / 2];
        for (int i = 0; i < hexStr.length() / 2; i++) {
            int high = Integer.parseInt(hexStr.substring(i * 2, i * 2 + 1), 16);
            int low = Integer.parseInt(hexStr.substring(i * 2 + 1, i * 2 + 2), 16);
            result[i] = (byte) (high * 16 + low);
        }
        return result;
    }
}

二、Activity 與版面

 package com.example.cheng.aesencrypt;

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    private EditText mInputET;
    private TextView mShowEncryputTV;
    private TextView mShowInputTV;
    private static final String PASSWORD_STRING = "12345678";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        mInputET = (EditText) findViewById(R.id.ase_input);
        mShowEncryputTV = (TextView) findViewById(R.id.show_oringe_encrypt);
        mShowInputTV = (TextView) findViewById(R.id.show_ase_encrypt);
    }

    /** 加密 */
    public void encrypt(View view) {
        String inputString = mInputET.getText().toString().trim();
        if (inputString.length() == 0) {
            Toast.makeText(this, "請輸入要加密的內容", Toast.LENGTH_SHORT).show();
            return;
        }
        String encryStr = Aes.encrypt(PASSWORD_STRING, inputString);
        mShowInputTV.setText(encryStr);
    }

    /** 解密 */
    public void decrypt(View view) {
        String encryptString = mShowInputTV.getText().toString().trim();
        if (encryptString.length() == 0) {
            Toast.makeText(this, "解密字串不能為空", Toast.LENGTH_SHORT).show();
            return;
        }
        String decryStr = Aes.decrypt(PASSWORD_STRING, encryptString);
        mShowEncryputTV.setText(decryStr);
    }
}
 <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center_vertical"
    android:orientation="vertical"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.cheng.aesencrypt.MainActivity">

    <EditText
        android:id="@+id/ase_input"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="輸入要加密的內容" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="encrypt"
        android:text="點擊進行 AES 加密" />

    <TextView
        android:id="@+id/show_ase_encrypt"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="顯示加密後的內容" />

    <Button
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:onClick="decrypt"
        android:text="點擊進行 AES 解密" />

    <TextView
        android:id="@+id/show_oringe_encrypt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:text="顯示解密後的內容" />
</LinearLayout>

三、執行結果

流程是:輸入明文 → 按加密 → 取得加密字串 → 按解密 → 還原成原本的明文。

四、關鍵重點說明

這個範例能跑通,靠的是幾個容易被忽略的細節:

1. 版本判斷是必須的。Android 4.2(API 17)修改了 SecureRandom 的取得方式,若不做版本判斷,在高版本裝置上會直接拿到不同的金鑰,導致解密失敗。這正是「同一份程式碼換裝置就不行」的主因。

2. 模式與填充要明確指定。寫成 AES/CBC/PKCS5Padding 而不是只寫 AES,可以避免不同 Provider 採用不同預設值。

3. 加密結果要轉成可安全傳輸的形式。這裡用十六進位字串,因為原始位元組含有不可列印字元,直接放進 JSON 或 URL 會出問題。實務上改用 Base64 更常見,也更省空間。

4. 建議用真機測試。模擬器的加密 Provider 實作與真機不盡相同,這個範例在模擬器上就未必能正確運作。

五、安全性提醒

這個實作的目的是示範流程,不能直接搬到 production 環境。有三個地方需要正視:

其一,IV 這裡用了全 0 的位元組陣列,等同於沒有 IV。在 CBC 模式下這會讓相同明文每次加密都得到相同結果,容易被用來比對。正式環境應為每次加密產生隨機 IV,並與密文一起存放。

其二,金鑰硬編碼在程式碼裡("12345678"),反編譯 APK 就能輕鬆取得。金鑰應交由 Keystore 系統管理。

其三,SHA1PRNG 這條路徑屬於歷史相容做法。目前的建議是直接改用 Android Keystore 產生並保管金鑰,讓密鑰永不離開安全硬體。

作者另外還提供了 DES、RSA 的示範專案:

https://github.com/chenguo4930/AndroidAES.git
https://github.com/chenguo4930/EncodeDemo.git

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