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

Android Studio JNI 開發入門:用 Native 層保護 DES 加密密鑰

編輯:關於 Android 程式設計

前言

開發過程中,為了資料傳輸安全,決定對資料進行 DES 加密後再與後端互動。但若把密鑰直接放在 Android 程式碼裡,即便做了混淆,反編譯後仍很容易被人取得,加密的安全度大打折扣。因此,考慮透過 JNI 由 Native 層回傳密鑰,藉此提升資料的安全性。

環境搭建

下載 NDK
透過 Android Studio 下載 NDK 插件:開啟 File -> Project Structure -> SDK Location -> Android NDK Location。若是第一次使用且尚未下載,紅色箭頭處會有下載安裝按鈕;也可選取藍色箭頭處的按鈕,指定已下載好的 NDK。設定成功後,會在 local.properties 檔中看到相應的路徑指向。

配置 NDK 環境變數
建立 NDK_HOME:右鍵「我的電腦 -> 內容 -> 進階系統設定 -> 環境變數 -> 系統變數 -> 新增」,建立一個名為 NDK_HOME 的變數,其值為上一步配置的 NDK 路徑。

接著在系統變數中找到 Path -> 編輯,把 %NDK_HOME% 加入其中。

驗證配置
在 cmd 下輸入 ndk-build 指令,若出現如下結果即代表配置成功:

建立 Native 程式碼

在 java 目錄下建立一個帶有 native 方法的 Java 檔

public class SmartCardJniUtil {
    // 載入 so 庫
    static {
        System.loadLibrary("SCJniUtil");
    }

    // 獲取密鑰
    public native String getKey();
}

透過 Build -> Make Project 編譯專案
成功後,在 app -> intermediates -> classes -> debug -> 個人專案路徑下,找到剛才 native 類別對應的 class 檔。

產生標頭檔
在 File -> Settings -> Plugins 下勾選 Terminal 插件,即可在 AS 內使用指令。先透過 cd app\src\main 跳到 main 目錄,再輸入:

javah -d jni -classpath E:\SDK\platforms\android-20\android.jar;.\build\intermediates\classes\debug com.a.b.c.SmartCardJniUtil

成功後會在 main 目錄下多出一個 jni 資料夾,並包含一個 .h 標頭檔:

建立 .c 檔
在 jni 目錄下右鍵 -> New -> C/C++ Source File 建立 SmartCardJniUtil.c,引入標頭檔並回傳密鑰:

#include "com_a_b_c_SmartCardJniUtil.h"

JNIEXPORT jstring JNICALL Java_com_a_b_c_SmartCardJniUtil_getKey
        (JNIEnv *env, jobject jobject1) {
    return (*env)->NewStringUTF(env, "1122334455667788");
}

在 build.gradle 中添加配置

buildTypes {
    release {
        minifyEnabled true
        proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        ndk {
            moduleName "SCJniUtil"                       // 生成的 so 名稱
            abiFilters "armeabi", "armeabi-v7a", "x86"   // 輸出這三種 ABI 架構下的 so 庫
        }
    }
    debug {
        ndk {
            moduleName "SCJniUtil"
            abiFilters "armeabi", "armeabi-v7a", "x86"
        }
    }
}

sourceSets {
    main {
        jniLibs.srcDirs = ['libs']
    }
}

清理並重新 Make 專案,即可產生 so 庫:

關於 Android.mk
過去用 Eclipse 開發 JNI 時,需要手動配置 Android.mk;而 Android Studio 會自動幫我們產生,無需自己建立。

在混淆檔中添加保留 native 方法的設定

-keepclasseswithmembernames class * {
    native <methods>;
}

使用方式

透過 JNI 獲取密鑰
完成以上步驟後,只需例項化 native 物件並呼叫方法即可取得密鑰:

SmartCardJniUtil jniUtil = new SmartCardJniUtil();
jniUtil.getKey(); // 獲取密鑰

DES 加解密工具類(配合上面取得的密鑰使用):

public class DesUtil {
    // 數據加密,算法(DES)
    public static String encryptBasedDes(String data, String keyStr) {
        keyStr = StringUtilsSimple.leftPad(keyStr, 16, "0");
        byte[] DES_KEY = ByteUtil.hexStr2Byte(keyStr);
        String encryptedData = null;
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.ENCRYPT_MODE, key, sr);
            encryptedData = ByteUtil.hexToStr(cipher.doFinal(data.getBytes()));
        } catch (Exception e) {
            throw new RuntimeException("加密錯誤,錯誤信息:", e);
        }
        return encryptedData;
    }

    // 數據解密,算法(DES)
    public static String decryptBasedDes(String cryptData, String keyStr) {
        keyStr = StringUtilsSimple.leftPad(keyStr, 16, "0");
        byte[] DES_KEY = ByteUtil.hexStr2Byte(keyStr);
        String decryptedData = null;
        try {
            SecureRandom sr = new SecureRandom();
            DESKeySpec deskey = new DESKeySpec(DES_KEY);
            SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
            SecretKey key = keyFactory.generateSecret(deskey);
            Cipher cipher = Cipher.getInstance("DES");
            cipher.init(Cipher.DECRYPT_MODE, key, sr);
            decryptedData = new String(cipher.doFinal(ByteUtil.hexStr2Byte(cryptData)));
        } catch (Exception e) {
            throw new RuntimeException("解密錯誤,錯誤信息:", e);
        }
        return decryptedData;
    }
}

其中 leftPad 為文字左右補位工具(將不足 16 位的密鑰左側補零),ByteUtil 則負責十六進位字串與位元組的互轉。透過把密鑰藏進 Native 層,即使 APK 被反編譯,攻擊者也難以直接從 Java 層取得加密密鑰,從而有效提升了資料傳輸的安全性。

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