zl程序教程

您现在的位置是:首页 >  移动开发

当前栏目

【Android 安全】DEX 加密 ( 代理 Application 开发 | 项目中配置 OpenSSL 开源库 | 使用 OpenSSL 开源库解密 dex 文件 )

2023-09-14 09:07:31 时间



参考博客 :


【Android 安全】DEX 加密 ( 支持多 DEX 的 Android 工程结构 ) 博客中介绍了 DEX 加密工程的基本结构 ,

app 是主应用 , 其 Module 类型是 “Phone & Tablet Module” ,

multiple-dex-core 是 Android 依赖库 , 其作用是解密并加载多 DEX 文件 , 其 Module 类型是 “Android Library” ,

multiple-dex-tools 是 Java 依赖库 , 其类型是 “Java or Kotlin Library” , 其作用是用于生成主 DEX ( 主 DEX 的作用就是用于解密与加载多 DEX ) , 并且还要为修改后的 APK 进行签名 ;


【Android 安全】DEX 加密 ( 代理 Application 开发 | multiple-dex-core 依赖库开发 | 配置元数据 | 获取 apk 文件并准备相关目录 ) 博客中讲解了 multiple-dex-core 依赖库开发 , 每次启动都要解密与加载 dex 文件 , 在该博客中讲解到了 获取 apk 文件 , 并准备解压目录 ;

【Android 安全】DEX 加密 ( 代理 Application 开发 | 解压 apk 文件 | 判定是否是第一次启动 | 递归删除文件操作 | 解压 Zip 文件操作 ) 博客中讲解了 apk 文件解压操作 ;

【Android 安全】DEX 加密 ( 代理 Application 开发 | 加载 dex 文件 | 反射获取系统的 Element[] dexElements )博客中讲解了 dex 文件加载第一阶段 , 获取系统中的 Element[] dexElements ;

【Android 安全】DEX 加密 ( 代理 Application 开发 | 加载 dex 文件 | 使用反射获取方法创建本应用的 dexElements | 各版本创建 dex 数组源码对比 ) 博客中讲解了讲解 dex 文件加载操作 第二阶段 , 创建本应用的 dex 文件数组 Element[] dexElements ;

【Android 安全】DEX 加密 ( 代理 Application 开发 | 加载 dex 文件 | 将系统的 dexElements 与 应用的 dexElements 合并 | 替换操作 ) 博客中讲解了剩余的两个操作 :

  • 系统加载的 Element[] dexElements 数组 与 我们 自己的 Element[] dexElements 数组 进行合并操作 ;
  • 替换 ClassLoader 加载过程中的 Element[] dexElements 数组 ( 封装在 DexPathList 中 )

【Android 安全】DEX 加密 ( Java 工具开发 | 加密解密算法 API | 编译代理 Application 依赖库 | 解压依赖库 aar 文件 ) ) 博客中介绍 加密解密算法 API , 编译代理 Application 依赖库 , 解压依赖库 aar 文件 ;

【Android 安全】DEX 加密 ( Java 工具开发 | 生成 dex 文件 | Java 命令行执行 ) 博客中介绍 使用 SDK 中的 dx 工具生成 dex 文件 ;


【Android 安全】DEX 加密 ( Java 工具开发 | 解压 apk 文件 | 加密生成 dex 文件 | 打包未签名 apk 文件 | 文件解压缩相关代码 ) 博客中讲解 将 app 主应用的 apk 文件解压 , 加密其中的 classes.dex 文件 , 并将代理 Application 依赖库中的 classes.dex 打包到未签名的 apk 文件中 ;

【Android 安全】DEX 加密 ( Java 工具开发 | apk 文件对齐 ) 博客中讲解 apk 文件对齐操作 ;

【Android 安全】DEX 加密 ( Java 工具开发 | apk 文件签名 ) 博客中讲解 apk 签名 ;

【Android 安全】DEX 加密 ( 代理 Application 开发 | 交叉编译 OpenSSL 开源库 ) 博客中 交叉编译了 Android 平台使用的密码库 OpenSSL ;


本博客中开始使用 交叉编译后的 OpenSSL 密码库 解码 被加密的 dex 文件 ;





一、项目中配置 OpenSSL 开源库



拷贝头文件与函数库到 代理 Application 依赖库中 , 拷贝到 src/main/cpp 目录下即可 ;

在这里插入图片描述


配置 CMakeLists.txt 构建脚本

cmake_minimum_required(VERSION 3.4.1)

# 配置编译选项, 编译类型 动态库, C++ 源码为 native-lib.c
add_library(
    openssl
    SHARED
    native-lib.c )

# 设置 openssl 函数库的静态库地址
set(LIB_DIR ${CMAKE_SOURCE_DIR}/lib/${ANDROID_ABI})
add_library(crypto STATIC IMPORTED)

# 预编译 openssl 静态库
set_target_properties(crypto PROPERTIES IMPORTED_LOCATION ${LIB_DIR}/libcrypto.a)

# 指定头文件路径
include_directories(include)

# 链接动态库
target_link_libraries(
    openssl
    crypto
    log )

在 Module 下的 build.gradle 中配置 NDK 编译选项 , 主要是配置两个 externalNativeBuild , 一个在 android 下 , 一个在 defaultConfig 下 ;

apply plugin: 'com.android.library'
apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "30.0.2"

    defaultConfig {
        minSdkVersion 16
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"

        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        consumerProguardFiles 'consumer-rules.pro'

        externalNativeBuild{
            cmake{
                // 配置要编译动态库的 CPU 架构, 这里编译 arm 和 x86 两个版本的动态库
                // arm64-v8a, armeabi-v7a, x86, x86_64
                abiFilters 'armeabi-v7a','x86'
            }
        }
    }

    externalNativeBuild{
        cmake{
            // 配置编译的 CMake 脚本位置, 默认当前目录是 app 目录
            // build.gradle 构建脚本所在目录
            path 'src/main/cpp/CMakeLists.txt'
        }
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }

}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.2.0'
    implementation 'androidx.core:core-ktx:1.3.2'
    implementation project(path: ':multiple-dex-tools')
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.2'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.3.0'
}




二、OpenSSL 开源库解密参考代码



OpenSSL 加密解密代码参考 OpenSSL 源码跟目录下 demos/evp/aesccm.c 官方示例代码 , 在 Android 的 jni 代码中按照下面示例代码中的 aes_ccm_decrypt 方法解密即可 ;

/*
 * Simple AES CCM test program, uses the same NIST data used for the FIPS
 * self test but uses the application level EVP APIs.
 */
#include <stdio.h>
#include <openssl/bio.h>
#include <openssl/evp.h>

/* AES-CCM test data from NIST public test vectors */

static const unsigned char ccm_key[] = {
    0xce, 0xb0, 0x09, 0xae, 0xa4, 0x45, 0x44, 0x51, 0xfe, 0xad, 0xf0, 0xe6,
    0xb3, 0x6f, 0x45, 0x55, 0x5d, 0xd0, 0x47, 0x23, 0xba, 0xa4, 0x48, 0xe8
};

static const unsigned char ccm_nonce[] = {
    0x76, 0x40, 0x43, 0xc4, 0x94, 0x60, 0xb7
};

static const unsigned char ccm_adata[] = {
    0x6e, 0x80, 0xdd, 0x7f, 0x1b, 0xad, 0xf3, 0xa1, 0xc9, 0xab, 0x25, 0xc7,
    0x5f, 0x10, 0xbd, 0xe7, 0x8c, 0x23, 0xfa, 0x0e, 0xb8, 0xf9, 0xaa, 0xa5,
    0x3a, 0xde, 0xfb, 0xf4, 0xcb, 0xf7, 0x8f, 0xe4
};

static const unsigned char ccm_pt[] = {
    0xc8, 0xd2, 0x75, 0xf9, 0x19, 0xe1, 0x7d, 0x7f, 0xe6, 0x9c, 0x2a, 0x1f,
    0x58, 0x93, 0x9d, 0xfe, 0x4d, 0x40, 0x37, 0x91, 0xb5, 0xdf, 0x13, 0x10
};

static const unsigned char ccm_ct[] = {
    0x8a, 0x0f, 0x3d, 0x82, 0x29, 0xe4, 0x8e, 0x74, 0x87, 0xfd, 0x95, 0xa2,
    0x8a, 0xd3, 0x92, 0xc8, 0x0b, 0x36, 0x81, 0xd4, 0xfb, 0xc7, 0xbb, 0xfd
};

static const unsigned char ccm_tag[] = {
    0x2d, 0xd6, 0xef, 0x1c, 0x45, 0xd4, 0xcc, 0xb7, 0x23, 0xdc, 0x07, 0x44,
    0x14, 0xdb, 0x50, 0x6d
};

void aes_ccm_encrypt(void)
{
    EVP_CIPHER_CTX *ctx;
    int outlen, tmplen;
    unsigned char outbuf[1024];
    printf("AES CCM Encrypt:\n");
    printf("Plaintext:\n");
    BIO_dump_fp(stdout, ccm_pt, sizeof(ccm_pt));
    ctx = EVP_CIPHER_CTX_new();
    /* Set cipher type and mode */
    EVP_EncryptInit_ex(ctx, EVP_aes_192_ccm(), NULL, NULL, NULL);
    /* Set nonce length if default 96 bits is not appropriate */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, sizeof(ccm_nonce),
                        NULL);
    /* Set tag length */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG, sizeof(ccm_tag), NULL);
    /* Initialise key and IV */
    EVP_EncryptInit_ex(ctx, NULL, NULL, ccm_key, ccm_nonce);
    /* Set plaintext length: only needed if AAD is used */
    EVP_EncryptUpdate(ctx, NULL, &outlen, NULL, sizeof(ccm_pt));
    /* Zero or one call to specify any AAD */
    EVP_EncryptUpdate(ctx, NULL, &outlen, ccm_adata, sizeof(ccm_adata));
    /* Encrypt plaintext: can only be called once */
    EVP_EncryptUpdate(ctx, outbuf, &outlen, ccm_pt, sizeof(ccm_pt));
    /* Output encrypted block */
    printf("Ciphertext:\n");
    BIO_dump_fp(stdout, outbuf, outlen);
    /* Finalise: note get no output for CCM */
    EVP_EncryptFinal_ex(ctx, outbuf, &outlen);
    /* Get tag */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_GET_TAG, 16, outbuf);
    /* Output tag */
    printf("Tag:\n");
    BIO_dump_fp(stdout, outbuf, 16);
    EVP_CIPHER_CTX_free(ctx);
}

void aes_ccm_decrypt(void)
{
    EVP_CIPHER_CTX *ctx;
    int outlen, tmplen, rv;
    unsigned char outbuf[1024];
    printf("AES CCM Derypt:\n");
    printf("Ciphertext:\n");
    BIO_dump_fp(stdout, ccm_ct, sizeof(ccm_ct));
    ctx = EVP_CIPHER_CTX_new();
    /* Select cipher */
    EVP_DecryptInit_ex(ctx, EVP_aes_192_ccm(), NULL, NULL, NULL);
    /* Set nonce length, omit for 96 bits */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_IVLEN, sizeof(ccm_nonce),
                        NULL);
    /* Set expected tag value */
    EVP_CIPHER_CTX_ctrl(ctx, EVP_CTRL_AEAD_SET_TAG,
                        sizeof(ccm_tag), (void *)ccm_tag);
    /* Specify key and IV */
    EVP_DecryptInit_ex(ctx, NULL, NULL, ccm_key, ccm_nonce);
    /* Set ciphertext length: only needed if we have AAD */
    EVP_DecryptUpdate(ctx, NULL, &outlen, NULL, sizeof(ccm_ct));
    /* Zero or one call to specify any AAD */
    EVP_DecryptUpdate(ctx, NULL, &outlen, ccm_adata, sizeof(ccm_adata));
    /* Decrypt plaintext, verify tag: can only be called once */
    rv = EVP_DecryptUpdate(ctx, outbuf, &outlen, ccm_ct, sizeof(ccm_ct));
    /* Output decrypted block: if tag verify failed we get nothing */
    if (rv > 0) {
        printf("Plaintext:\n");
        BIO_dump_fp(stdout, outbuf, outlen);
    } else
        printf("Plaintext not available: tag verify failed.\n");
    EVP_CIPHER_CTX_free(ctx);
}

int main(int argc, char **argv)
{
    aes_ccm_encrypt();
    aes_ccm_decrypt();
}




三、解密 dex 文件的 Java 代码



该类仅作为调用 Jni 中的 OpenSSL 解密函数的桥梁 ;

package kim.hsl.multipledex;

import java.io.File;
import java.io.RandomAccessFile;

public class OpenSSL {
    static {
        System.loadLibrary("openssl");
    }

    /**
     * 从文件中读取 Byte 数组
     * @param file
     * @return
     * @throws Exception
     */
    public static byte[] getBytes(File file) throws Exception {
        RandomAccessFile r = new RandomAccessFile(file, "r");
        byte[] buffer = new byte[(int) r.length()];
        r.readFully(buffer);
        r.close();
        return buffer;
    }

    /**
     * 调用 OpenSSL 解密 dex 文件
     * @param data
     * @param path
     */
    public static native void decrypt(byte[] data, String path);
}





四、解密 dex 文件的 Jni 代码



解密 dex 文件的方法 , 调用 OpenSSL 开源库中的 api ;

#include <jni.h>
#include <stdio.h>
#include <android/log.h>
#include <malloc.h>
#include <string.h>
#include <openssl/evp.h>
#include "logging_macros.h"

//密钥
static uint8_t *userkey = "abcdefghijklmnop";

JNIEXPORT void JNICALL
Java_kim_hsl_multipledex_OpenSSL_decrypt(JNIEnv *env, jclass clazz, jbyteArray data, jstring path) {

    // 将 Java Byte 数组转为 C 数组
    jbyte *src = (*env)->GetByteArrayElements(env, data, NULL);
    // 将 Java String 字符串转为 C char* 字符串
    const char *filePath = (*env)->GetStringUTFChars(env, path, 0);
    // 获取 Java Byte 数组长度
    int srcLen = (*env)->GetArrayLength(env, data);

    /*
     * 下面的代码是从 OpenSSL 源码跟目录下 demos/evp/aesccm.c 中拷贝并修改
     */

    // 加密解密的上下文
    EVP_CIPHER_CTX *ctx;
    int outlen, tmplen;
    unsigned char outbuf[1024];
    // 创建加密解密上下文
    ctx = EVP_CIPHER_CTX_new();

    /* Select cipher 配置上下文解码参数
     * 配置加密模式 :
     * Java 中的加密算法类型 "AES/ECB/PKCS5Padding" , 使用 ecb 模式
     * EVP_aes_192_ecb() 配置 ecb 模式
     * AES 有五种加密模式 : CBC、ECB、CTR、OCF、CFB
     * 配置密钥 :
     * Java 中定义的密钥是 "kimhslmultiplede"
     */
    EVP_DecryptInit_ex(ctx, EVP_aes_192_ecb(), NULL, "kimhslmultiplede", NULL);


    // 申请解密输出数据内存, 申请内存长度与密文长度一样即可
    // AES 加密密文比明文要长
    uint8_t *out = malloc(srcLen);
    // 将申请的内存设置为 0
    memset(out, 0, srcLen);

    // 记录解密总长度
    int totalLen = 0;

    /*
     * 解密操作
     * int EVP_DecryptUpdate(EVP_CIPHER_CTX *ctx, unsigned char *out,
                                 int *outl, const unsigned char *in, int inl);
     * 解密 inl 长度的 in , 解密为 outl 长度的 out
     * 解密的输入数据是 src, 长度为 srcLen 字节, 注意该长度是 int 类型
     * 解密的输出数据是 out, 长度为 srcLen 字节, 注意该长度是 int* 指针类型
     */
    EVP_DecryptUpdate(ctx, out, &outlen, src, srcLen);
    totalLen += outlen; //更新总长度

    /*
     * int EVP_DecryptFinal_ex(EVP_CIPHER_CTX *ctx, unsigned char *outm,
                                   int *outl);
     * 解密时, 每次解密 16 字节, 如果超过了 16 字节 , 就会剩余一部分无法解密,
     * 之前的 out 指针已经解密了 outlen 长度, 此时接着后续解密, 指针需要进行改变 out + outlen
     * 此时需要调用该函数 , 解密剩余内容
     */
    EVP_DecryptFinal_ex(ctx, out + outlen, &outlen);
    totalLen += outlen; //更新总长度, 此时 totalLen 就是总长度

    // 解密完成, 释放上下文对象
    EVP_CIPHER_CTX_free(ctx);

    // 将解密出的明文, 写出到给定的 Java 文件中
    FILE *file = fopen(path, "wb");
    // 写出 out 指针指向的数据 , 写出个数 totalLen * 1 , 写出到 file 文件中
    fwrite(out, totalLen, 1, file);
    // 关闭文件
    fclose(file);
    // 释放解密出的密文内存
    free(out);

    // 释放 Java 引用
    (*env)->ReleaseByteArrayElements(env, data, src, 0);
    (*env)->ReleaseStringUTFChars(env, path, path);

}