namanONcode/Anchor-pq

GitHub: namanONcode/Anchor-pq

面向Android应用的后量子完整性框架,通过Merkle树与服务器锚定验证防止应用被篡改。

Stars: 3 | Forks: 0

# 🛡️ AnchorPQ - Android 后量子完整性框架 Anchor-pq Gradle Plugin - Android Post-Quantum Integrity Framework | Product Hunt [![CI Build](https://static.pigsec.cn/wp-content/uploads/repos/2026/03/c0dfce45b0213932.svg)](https://github.com/namanoncode/AndroidPostQuantumIntegrityFramework/actions/workflows/ci.yml) [![CodeQL](https://static.pigsec.cn/wp-content/uploads/repos/2026/03/bcab65b189213936.svg)](https://github.com/namanoncode/AndroidPostQuantumIntegrityFramework/actions/workflows/codeql.yml) [![License](https://img.shields.io/badge/License-Apache%202.0-blue.svg)](LICENSE) [![Gradle Plugin](https://img.shields.io/badge/Gradle-9.3%2B-green.svg)](https://gradle.org/) [![Android](https://img.shields.io/badge/Android-API%2026%2B-brightgreen.svg)](https://developer.android.com/) [![Quarkus](https://img.shields.io/badge/Quarkus-3.8%2B-red.svg)](https://quarkus.io/) 一个综合性的框架,利用 **Merkle 树** 和 **后量子密码学 (ML-KEM/CRYSTALS-Kyber)**,为 Android 应用提供**构建时完整性验证**和**运行时服务器锚定验证**。 ## 🏗️ 项目结构 此 monorepo 包含三个主要组件: | 组件 | 描述 | 文档 | |-----------|-------------|---------------| | **[Gradle Plugin](/)** | Android 应用的构建时 Merkle 树计算 | 本 README | | **[Verification Server](anchorpq-server/)** | 用于运行时完整性验证的 Quarkus 后端 | [Server README](SERVER-README.md) | | **[Demo App](anchorpq-demo-app/)** | 具备 ML-KEM 功能的生产级 Android 演示 | [Demo README](anchorpq-demo-app/README.md) | ``` AndroidPostQuantumIntegrityFramework/ ├── src/ # Gradle Plugin source code ├── anchorpq-server/ # Quarkus Verification Server ├── anchorpq-demo-app/ # Production-grade Android Demo App ├── scripts/ # Helper scripts (E2E tests, DB seeding) ├── docker-compose.yml # Docker setup for server + PostgreSQL └── .github/workflows/ # CI/CD pipeline ``` ## 📋 目录 - [概述](#-overview) - [功能特性](#-features) - [架构](#-architecture) - [工作原理](#-how-it-works) - [安装说明](#-installation) - [快速开始](#-quick-start) - [配置选项](#-configuration) - [生成输出](#-generated-outputs) - [运行时集成](#-runtime-integration) - [服务端验证](#-server-side-verification) - [验证服务器](#-verification-server) - [完整示例应用](#-complete-example-app) - [API 参考](#-api-reference) - [安全模型](#-security-model) - [故障排除](#-troubleshooting) - [环境要求](#-requirements) - [许可证](#-license) ## 🌟 概述 ### 这个框架是什么? Android 后量子完整性框架包括: 1. **Gradle Plugin (构建时)**:计算应用编译代码的加密指纹(Merkle root) 2. **Verification Server (运行时)**:使用服务器锚定信任模型验证应用完整性 3. **Post-Quantum Security**:使用 ML-KEM (CRYSTALS-Kyber) 进行抗量子通信 ### 为什么需要它? - **检测篡改**:立即知道您的 APK 是否已被修改 - **防止盗版**:阻止未经授权重新分发修改后的应用 - **合规性**:满足敏感应用的安全要求 - **面向未来**:后量子密码学可防止量子计算机攻击 ## ✨ 功能特性 | 功能 | 描述 | |---------|-------------| | 🌳 **Merkle Tree Computation** | 所有编译后 `.class` 文件的确定性哈希树 | | 📄 **Integrity Metadata** | 包含构建信息和 Merkle root 的 JSON/XML 文件 | | 📱 **Assets Integration** | 自动将完整性数据打包到您的 APK 中 | | 🔐 **ML-KEM Encryption** | 用于运行时报告的后量子安全通信 | | 🤖 **AGP 9+ Compatible** | 兼容内置 Kotlin 的 Android Gradle Plugin 9.x | | ⚡ **Automatic Integration** | 自动挂钩到标准构建生命周期 | | 🔧 **Configurable** | 多种哈希算法和输出格式 | ## 🏗️ 架构 ``` ┌─────────────────────────────────────────────────────────────────────────────┐ │ BUILD TIME │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────┐ ┌────────────────────┐ ┌──────────────────────┐ │ │ │ Compile │ │ GenerateMerkle │ │ GenerateMetadata │ │ │ │ Kotlin/ │───▶│ Task │───▶│ Task │ │ │ │ Java │ │ (Hash all .class) │ │ (Create JSON/XML) │ │ │ └──────────────┘ └────────────────────┘ └──────────────────────┘ │ │ │ │ │ │ ▼ ▼ │ │ ┌────────────────┐ ┌─────────────────┐ │ │ │ merkle-root.txt│ │ integrity.json │ │ │ │ (SHA-256 hash) │ │ (Full metadata) │ │ │ └────────────────┘ └─────────────────┘ │ │ │ │ │ ┌───────────────────────────┘ │ │ ▼ │ │ ┌─────────────────────┐ │ │ │ CopyIntegrityAssets │ │ │ │ Task │ │ │ │ (Copy to APK assets)│ │ │ └─────────────────────┘ │ │ │ ├─────────────────────────────────────────────────────────────────────────────┤ │ RUNTIME │ ├─────────────────────────────────────────────────────────────────────────────┤ │ │ │ ┌──────────────┐ ┌────────────────────┐ ┌──────────────────────┐ │ │ │ App Starts │ │ Read integrity │ │ Compare with │ │ │ │ │───▶│ .json from assets │───▶│ server expected │ │ │ │ │ │ │ │ Merkle root │ │ │ └──────────────┘ └────────────────────┘ └──────────────────────┘ │ │ │ │ │ ┌───────────────────────────┘ │ │ ▼ │ │ ┌─────────────────────┐ │ │ │ MATCH? │ │ │ │ ✅ Allow app │ │ │ │ ❌ Block/Alert │ │ │ └─────────────────────┘ │ │ │ │ Optional: ML-KEM encrypted communication with verification server │ │ │ └─────────────────────────────────────────────────────────────────────────────┘ ``` ## 🔍 工作原理 ### 步骤 1: Merkle 树构建 该插件从您编译后的字节码创建一个二进制哈希树: ``` ┌─────────────────┐ │ Merkle Root │ │ (Final Hash) │ └────────┬────────┘ │ ┌──────────────┴──────────────┐ │ │ ┌─────┴─────┐ ┌─────┴─────┐ │ Hash AB │ │ Hash CD │ └─────┬─────┘ └─────┬─────┘ │ │ ┌──────┴──────┐ ┌──────┴──────┐ │ │ │ │ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ │Hash A │ │Hash B │ │Hash C │ │Hash D │ └───┬───┘ └───┬───┘ └───┬───┘ └───┬───┘ │ │ │ │ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ ┌───┴───┐ │A.class│ │B.class│ │C.class│ │D.class│ └───────┘ └───────┘ └───────┘ └───────┘ ``` **属性:** - ✅ **Deterministic**:相同的代码总是产生相同的 root - ✅ **Tamper-evident**:对任何文件的任何更改都会改变 root - ✅ **Efficient**:使用 Merkle 证明进行 O(log n) 验证 ### 步骤 2: 文件排除 该插件会自动排除每次构建都会更改的生成文件: | 排除模式 | 原因 | |-----------------|--------| | `R.class`, `R$*.class` | 资源 ID 经常变化 | | `BuildConfig.class` | 包含构建特定的值 | | `*$$*.class` | Dagger/Hilt 生成的代码 | | `*_Factory.class` | 依赖注入工厂 | | `Hilt_*.class` | Hilt 生成的类 | ### 步骤 3: 运行时验证流程 ``` ┌─────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ App Start │────▶│ Load Merkle │────▶│ Send to Server │ │ │ │ Root from │ │ for Validation │ │ │ │ assets/ │ │ │ └─────────────┘ │ integrity.json │ └────────┬────────┘ └─────────────────┘ │ ▼ ┌─────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Block App │◀────│ Roots Don't │◀────│ Server Compare │ │ Show Error │ │ Match! │ │ with Expected │ └─────────────┘ └─────────────────┘ └────────┬────────┘ │ ┌─────────────────┐ │ │ Roots Match! │◀─────────────┘ │ Allow App │ └─────────────────┘ ``` ## 📦 安装说明 一个用于 Android 应用的后量子完整性验证插件,使用 Merkle 树和 ML-KEM (CRYSTALS-Kyber)。 ### 使用 plugins DSL 使用 plugins DSL 将此插件添加到您的构建中: ``` plugins { id("io.github.namanoncode.anchorpq") version "1.0.0" } ``` 另请参阅: 将插件添加到构建逻辑中以在预编译脚本插件中使用。 有关更多信息,请参阅相关文档。 将此插件作为依赖项添加到 `/build.gradle(.kts)`: ``` dependencies { implementation("io.github.namanoncode.anchorpq:io.github.namanoncode.anchorpq.gradle.plugin:1.0.0") } ``` 然后可以在预编译脚本插件中应用它: ``` plugins { id("io.github.namanoncode.anchorpq") } ``` ### 传统的插件应用方法 有关更多信息,请参阅相关文档。 ``` buildscript { repositories { gradlePluginPortal() } dependencies { classpath("io.github.namanoncode.anchorpq:io.github.namanoncode.anchorpq.gradle.plugin:1.0.0") } } apply(plugin = "io.github.namanoncode.anchorpq") ``` ### 方法 1: 本地 JAR (开发用) **步骤 1:** 构建插件 JAR ``` cd AndroidPostQuantumIntegrityFramework ./gradlew clean build ``` 这将创建:`build/libs/AndroidPostQuantumIntegrityFramework-1.0.0.jar` **步骤 2:** 在您的 Android 项目的 `build.gradle.kts` (根级别) 中: ``` // Top-level build file buildscript { repositories { google() mavenCentral() // Local plugin JAR flatDir { dirs("path/to/AndroidPostQuantumIntegrityFramework/build/libs") } } dependencies { classpath("com.android.tools.build:gradle:9.0.1") // Include the local integrity plugin JAR classpath(files("path/to/AndroidPostQuantumIntegrityFramework/build/libs/AndroidPostQuantumIntegrityFramework-1.0.0.jar")) // Plugin dependencies (required) classpath("org.bouncycastle:bcprov-jdk18on:1.83") classpath("org.bouncycastle:bcpkix-jdk18on:1.83") classpath("com.google.code.gson:gson:2.13.2") } } plugins { id("com.android.application") version "9.0.1" apply false } ``` **步骤 3:** 在您的 Android 项目的 `settings.gradle.kts` 中: ``` pluginManagement { repositories { google() mavenCentral() gradlePluginPortal() // Include local plugin flatDir { dirs("path/to/AndroidPostQuantumIntegrityFramework/build/libs") } } } dependencyResolutionManagement { repositoriesMode.set(RepositoriesMode.FAIL_ON_PROJECT_REPOS) repositories { google() mavenCentral() } } rootProject.name = "YourApp" include(":app") ``` ### 方法 2: Maven Local (推荐团队使用) ``` cd AndroidPostQuantumIntegrityFramework ./gradlew publishToMavenLocal ``` 然后在您的项目中: ``` // settings.gradle.kts pluginManagement { repositories { mavenLocal() google() mavenCentral() gradlePluginPortal() } } ``` ## 🚀 快速开始 ### 步骤 1: 应用插件 在您的应用模块的 `app/build.gradle.kts` 中: ``` plugins { id("com.android.application") id("io.github.namanoncode.anchorpq") // Add this line } android { namespace = "com.yourcompany.yourapp" compileSdk = 34 defaultConfig { applicationId = "com.yourcompany.yourapp" minSdk = 26 targetSdk = 34 versionCode = 1 versionName = "1.0.0" // Add MERKLE_ROOT placeholder to BuildConfig buildConfigField("String", "MERKLE_ROOT", "\"GENERATED_AT_BUILD_TIME\"") } buildFeatures { buildConfig = true } // Required for Bouncy Castle JAR files packaging { resources { excludes += listOf( "META-INF/versions/9/OSGI-INF/MANIFEST.MF", "META-INF/BCKEY.DSA", "META-INF/BCKEY.SF" ) } } } // Configure the Anchor PQ Integrity plugin anchorpq { enabled = true algorithm = "SHA-256" injectBuildConfig = true version = android.defaultConfig.versionName ?: "1.0.0" mlKemEnabled = true } dependencies { // Bouncy Castle for ML-KEM (post-quantum crypto) implementation("org.bouncycastle:bcprov-jdk18on:1.83") implementation("org.bouncycastle:bcpkix-jdk18on:1.83") // Gson for JSON parsing implementation("com.google.code.gson:gson:2.13.2") // Your other dependencies... } ``` ### 步骤 2: 创建 gradle.properties 在您的项目根目录中创建或更新 `gradle.properties`: ``` # AndroidX 设置 android.useAndroidX=true android.enableJetifier=false # Kotlin kotlin.code.style=official # 构建性能 org.gradle.jvmargs=-Xmx2048m -Dfile.encoding=UTF-8 org.gradle.parallel=true ``` ### 步骤 3: 创建 local.properties 在您的项目根目录中创建 `local.properties`: ``` sdk.dir=/path/to/your/Android/Sdk ``` ### 步骤 4: 构建您的应用 ``` ./gradlew assembleDebug ``` 您应该看到如下输出: ``` > Task :app:generateMerkleRootDebug Generating Merkle root for variant: debug Classes directory: .../app/build/intermediates/javac/debug/classes Found 42 class files for integrity computation Merkle root computed: 45e2f3b4eab4253af3de4887a435b71cb6694f9d0b07026e23c9fdfda50afaa1 > Task :app:generateIntegrityMetadataDebug Generating integrity metadata for variant: debug Integrity metadata written to: .../app/build/anchorpq/debug/integrity.json > Task :app:copyIntegrityAssetsDebug Copied integrity.json to: .../app/src/main/assets/integrity.json ``` ## ⚙️ 配置选项 ### 完整配置选项 ``` anchorpq { // Enable/disable the plugin entirely // Default: true enabled = true // Hash algorithm for Merkle tree computation // Options: "SHA-256", "SHA-384", "SHA-512", "SHA3-256", "SHA3-512" // Default: "SHA-256" algorithm = "SHA-256" // Inject MERKLE_ROOT into BuildConfig // Default: true injectBuildConfig = true // Application version (included in metadata) // Default: "1.0.0" version = "1.0.0" // Optional: Signing certificate SHA-256 fingerprint // This helps verify the app was signed with the expected key signerFingerprint = "AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99:AA:BB:CC:DD:EE:FF:00:11:22:33:44:55:66:77:88:99" // Enable ML-KEM (post-quantum) encryption for runtime reporting // Default: false mlKemEnabled = true // Backend endpoint for integrity reporting (optional) reportingEndpoint = "https://api.yourserver.com/verify" } ``` ### 算法比较 | 算法 | 哈希大小 | 安全级别 | 性能 | |-----------|-----------|----------------|-------------| | SHA-256 | 256 位 | 标准 | ⚡ 快速 | | SHA-384 | 384 位 | 高 | ⚡ 快速 | | SHA-512 | 512 位 | 极高 | ⚡ 快速 | | SHA3-256 | 256 位 | 抗量子 | 🔄 中等 | | SHA3-512 | 512 位 | 抗量子 | 🔄 中等 | ## 📁 生成输出 构建后,插件会生成以下文件: ### 1. Merkle Root 文件 **位置:** `app/build/anchorpq/{variant}/merkle-root.txt` ``` 45e2f3b4eab4253af3de4887a435b71cb6694f9d0b07026e23c9fdfda50afaa1 ``` ### 2. 完整性元数据 (JSON) **位置:** `app/build/anchorpq/{variant}/integrity.json` ``` { "version": "1.0.0", "variant": "debug", "hashAlgorithm": "SHA-256", "merkleRoot": "45e2f3b4eab4253af3de4887a435b71cb6694f9d0b07026e23c9fdfda50afaa1", "timestamp": "2026-02-18T15:10:52.044713221Z", "leafCount": 42, "plugin": { "name": "Anchor PQ Integrity Plugin", "pluginVersion": "1.0.0" } } ``` ### 3. 完整性元数据 (XML) **位置:** `app/build/anchorpq/{variant}/integrity.xml` ``` 1.0.0 debug SHA-256 45e2f3b4eab4253af3de4887a435b71cb6694f9d0b07026e23c9fdfda50afaa1 2026-02-18T15:10:52.044713221Z ``` ### 4. APK Assets **APK 内位置:** `assets/integrity.json` `integrity.json` 会自动复制到您应用的 assets 文件夹并打包到 APK 中。 ## 📱 运行时集成 ### 在您的应用中读取 Merkle Root 创建一个 Application 类来读取和缓存 Merkle root: ``` package com.yourcompany.yourapp import android.app.Application import android.util.Log import com.google.gson.Gson import java.io.InputStreamReader class MyApplication : Application() { companion object { private const val TAG = "IntegrityCheck" private const val INTEGRITY_ASSET_FILE = "integrity.json" @Volatile var integrityVerified: Boolean = false private set } private var cachedMerkleRoot: String? = null override fun onCreate() { super.onCreate() Log.i(TAG, "App starting with Merkle root: ${getMerkleRoot()}") } /** * Get the Merkle root from assets/integrity.json */ fun getMerkleRoot(): String { cachedMerkleRoot?.let { return it } try { assets.open(INTEGRITY_ASSET_FILE).use { inputStream -> InputStreamReader(inputStream).use { reader -> val data = Gson().fromJson(reader, IntegrityMetadata::class.java) data?.merkleRoot?.let { cachedMerkleRoot = it Log.i(TAG, "Loaded Merkle root: ${it.take(16)}...") return it } } } } catch (e: Exception) { Log.e(TAG, "Failed to load integrity.json: ${e.message}") } return "UNKNOWN" } data class IntegrityMetadata( val version: String?, val variant: String?, val hashAlgorithm: String?, val merkleRoot: String?, val timestamp: String?, val leafCount: Int? ) fun setVerificationResult(verified: Boolean) { integrityVerified = verified } } ``` 别忘了在 `AndroidManifest.xml` 中注册您的 Application 类: ``` ``` ### 在应用启动时验证完整性 创建一个 Activity,在允许访问之前验证完整性: ``` package com.yourcompany.yourapp import android.content.Intent import android.os.Bundle import android.util.Log import androidx.appcompat.app.AppCompatActivity import androidx.lifecycle.lifecycleScope import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.delay import kotlinx.coroutines.launch import kotlinx.coroutines.withContext class IntegrityCheckActivity : AppCompatActivity() { override fun onCreate(savedInstanceState: Bundle?) { super.onCreate(savedInstanceState) setContentView(R.layout.activity_integrity_check) verifyIntegrity() } private fun verifyIntegrity() { lifecycleScope.launch { val app = application as MyApplication val merkleRoot = app.getMerkleRoot() // Send to your verification server val result = withContext(Dispatchers.IO) { verifyWithServer( merkleRoot = merkleRoot, version = BuildConfig.VERSION_NAME, variant = BuildConfig.BUILD_TYPE ) } if (result.isVerified) { app.setVerificationResult(true) proceedToMainActivity() } else { showTamperingDetected(result.reason) } } } private suspend fun verifyWithServer( merkleRoot: String, version: String, variant: String ): VerificationResult { // Implement your server verification here // For demo, we'll simulate a successful verification delay(1000) return VerificationResult(true, null) } private fun proceedToMainActivity() { startActivity(Intent(this, MainActivity::class.java)) finish() } private fun showTamperingDetected(reason: String?) { // Show error UI and block the app Log.e("Integrity", "Tampering detected: $reason") } data class VerificationResult( val isVerified: Boolean, val reason: String? ) } ``` ## 🖥️ 服务端验证 ### 预期请求格式 您的应用应向您的验证服务器发送 POST 请求: ``` { "merkle_root": "45e2f3b4eab4253af3de4887a435b71cb6694f9d0b07026e23c9fdfda50afaa1", "version": "1.0.0", "variant": "release", "package_name": "com.yourcompany.yourapp", "timestamp": 1708268452000 } ``` ### 预期响应格式 ``` { "verified": true, "message": "Integrity verified successfully", "expected_root": "45e2f3b4eab4253af3de4887a435b71cb6694f9d0b07026e23c9fdfda50afaa1" } ``` 或者如果验证失败: ``` { "verified": false, "message": "Application has been tampered with! Merkle root mismatch.", "expected_root": "abc123..." } ``` ### 🖥️ 示例 AnchorPQ Server (推荐) 该仓库提供了一个完整的、生产就绪的 **AnchorPQ Verification Server**,由 Quarkus 构建。要运行它: ``` # 使用 Docker Compose 启动服务器和 PostgreSQL 数据库 docker-compose up --build # 或者使用 Maven 运行 (要求 PostgreSQL 运行在 localhost:5432) cd anchorpq-server ./mvnw compile quarkus:dev ``` 有关更多详细信息,请参阅下方的 [服务器配置](#-verification-server)。 ## 📚 完整示例应用 ### AnchorPQ 演示应用 `anchorpq-demo-app/` 目录中包含了一个完整的生产级演示应用。该演示展示了具有真实后量子密码学的完整完整性验证流程。 **功能:** - 🔐 真实的 ML-KEM (CRYSTALS-Kyber) 密钥封装 - 🔒 完整性载荷的 AES-256-GCM 加密 - 🌲 Merkle root 显示和验证 - 📱 带状态指示器的 Material Design UI - 🧪 单元测试和插桩测试 **快速开始:** ``` # 1. 在本地构建并发布插件 ./gradlew publishToMavenLocal # 2. 启动验证服务器 docker-compose up --build # 3. 构建 demo app cd anchorpq-demo-app ./gradlew assembleDebug # 4. 安装到模拟器 adb install app/build/outputs/apk/debug/app-debug.apk ``` **演示应用架构:** ``` anchorpq-demo-app/ ├── app/ │ ├── src/main/java/com/anchorpq/demo/ │ │ ├── crypto/ # ML-KEM client implementation │ │ │ ├── MLKemClient.kt │ │ │ └── IntegrityEncryptionService.kt │ │ ├── model/ # API data models │ │ ├── network/ # Retrofit API client │ │ └── ui/ # MainActivity & ViewModel │ └── build.gradle.kts # Plugin integration ├── build.gradle.kts └── README.md # Detailed documentation ``` 有关完整文档,请参阅 [anchorpq-demo-app/README.md](anchorpq-demo-app/README.md)。 ### 验证流程演示 当您在演示应用中点击 "Verify Integrity" 时: ``` ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Demo App │────▶│ Fetch ML-KEM │────▶│ Encapsulate │ │ Click Verify │ │ Public Key │ │ Shared Secret │ └─────────────────┘ └─────────────────┘ └─────────────────┘ │ ▼ ┌─────────────────┐ ┌─────────────────┐ ┌─────────────────┐ │ Display Result │◀────│ Server Returns │◀────│ Encrypt & │ │ APPROVED/ │ │ APPROVED/ │ │ Send Payload │ │ REJECTED │ │ REJECTED │ │ │ └─────────────────┘ └─────────────────┘ └─────────────────┘ ``` ### 旧版示例 (仅供参考) 下面展示了一个更简单的示例应用结构以供参考: ``` example-android-app/ ├── app/ │ ├── build.gradle.kts # App build config with plugin │ ├── proguard-rules.pro # ProGuard rules │ └── src/main/ │ ├── AndroidManifest.xml │ ├── assets/ │ │ └── integrity.json # Generated at build time │ ├── java/com/example/secureapp/ │ │ ├── SecureApplication.kt # Reads Merkle root │ │ ├── IntegrityCheckActivity.kt # Verifies on startup │ │ ├── IntegrityVerifier.kt # Server communication │ │ ├── MainActivity.kt # Main app (after verification) │ │ └── CompromisedActivity.kt # Shown if tampered │ └── res/ │ ├── layout/ │ │ ├── activity_integrity_check.xml │ │ ├── activity_main.xml │ │ └── activity_compromised.xml │ └── values/ │ ├── colors.xml │ ├── strings.xml │ └── themes.xml ├── build.gradle.kts # Root build config ├── settings.gradle.kts # Project settings ├── gradle.properties # Gradle properties └── local.properties # SDK location ``` ### 构建示例应用 ``` # 从仓库根目录 cd anchorpq-demo-app # 构建 debug APK ./gradlew assembleDebug # APK 位于: # app/build/outputs/apk/debug/app-debug.apk ``` ## 📖 API 参考 ### Gradle Tasks | 任务名称 | 描述 | |-----------|-------------| | `generateMerkleRootDebug` | 计算 debug 变体的 Merkle root | | `generateMerkleRootRelease` | 计算 release 变体的 Merkle root | | `generateIntegrityMetadataDebug` | 为 debug 生成 integrity.json | | `generateIntegrityMetadataRelease` | 为 release 生成 integrity.json | | `copyIntegrityAssetsDebug` | 将 integrity.json 复制到 debug assets | | `copyIntegrityAssetsRelease` | 将 integrity.json 复制到 release assets | ### 手动运行任务 ``` # 仅生成 Merkle root ./gradlew :app:generateMerkleRootDebug # 生成所有 integrity 文件 ./gradlew :app:generateIntegrityMetadataDebug # 完整构建 (自动运行所有任务) ./gradlew :app:assembleDebug ``` ### MerkleTree 类 (Java API) ``` // Create a Merkle tree from leaf hashes List leafHashes = new ArrayList<>(); leafHashes.add(HashUtils.hash(file1Content, "SHA-256")); leafHashes.add(HashUtils.hash(file2Content, "SHA-256")); MerkleTree tree = new MerkleTree(leafHashes, "SHA-256"); // Get the root hash String rootHex = tree.getRootHex(); byte[] rootBytes = tree.getRoot(); // Get tree statistics int height = tree.getHeight(); int leafCount = tree.getLeafCount(); // Generate proof for a leaf MerkleTree.ProofNode[] proof = tree.generateProof(0); // Verify a proof boolean valid = tree.verifyProof(leafHash, proof); ``` ### HashUtils 类 (Java API) ``` // Hash a byte array byte[] hash = HashUtils.hash(data, "SHA-256"); // Hash concatenation of two hashes byte[] combined = HashUtils.hashConcat(left, right, "SHA-256"); // Convert to hex string String hex = HashUtils.toHex(hash); // Check if algorithm is supported boolean supported = HashUtils.isAlgorithmSupported("SHA-256"); ``` ## 🔒 安全模型 ### 此框架可以防御的威胁 | 威胁 | 保护措施 | 级别 | |--------|------------|-------| | APK 修改 | Merkle root 变化 | ✅ 强 | | 代码注入 | 哈希验证检测更改 | ✅ 强 | | 重放攻击 | 请求中的时间戳 + nonce | ✅ 强 | | 网络窃听 | ML-KEM 加密 (可选) | ✅ 强 | | 量子攻击 | 后量子密码学 | ✅ 面向未来 | ### 此框架无法防御的威胁 | 威胁 | 原因 | 缓解措施 | |--------|-----|------------| | Runtime Hooking | 无运行时保护 | 使用混淆、native 代码 | | Root/Jailbreak | 可以绕过验证 | 使用 SafetyNet/Play Integrity | | 内存篡改 | 无内存保护 | 使用硬件安全模块 | | 密钥提取 | 密钥位于应用内存中 | 使用 Android Keystore/HSM | | 构建环境受损 | 信任假设 | 安全的 CI/CD 流水线 | ### 信任假设 1. **Build Environment**:运行 `./gradlew build` 的机器未受损 2. **Plugin Integrity**:Anchor PQ 插件 JAR 是真实的 3. **Server Security**:您的验证服务器已正确保护 4. **Key Management**:ML-KEM 密钥已得到适当保护 ## 🔧 故障排除 ### 常见问题 #### 1. "Plugin not found" 错误 ``` Plugin [id: 'io.github.namanoncode.anchorpq'] was not found ``` **解决方案:** 确保插件 JAR 位于 classpath 中: ``` buildscript { dependencies { classpath(files("path/to/AndroidPostQuantumIntegrityFramework-1.0.0.jar")) } } ``` #### 2. "Classes directory does not exist" 错误 ``` Classes directory does not exist: .../intermediates/javac/debug/classes ``` **解决方案:** 插件在编译之前运行。确保您正在运行完整构建: ``` ./gradlew clean assembleDebug ``` #### 3. Bouncy Castle 合并冲突 ``` 3 files found with path 'META-INF/versions/9/OSGI-INF/MANIFEST.MF' ``` **解决方案:** 在您的 `build.gradle.kts` 中添加 packaging 选项: ``` android { packaging { resources { excludes += listOf( "META-INF/versions/9/OSGI-INF/MANIFEST.MF", "META-INF/BCKEY.DSA", "META-INF/BCKEY.SF" ) } } } ``` #### 4. JDK 兼容性问题 ``` Error while executing process jlink with arguments... ``` **解决方案:** 使用标准的 JDK 17 (例如 Eclipse Temurin)。GraalVM JDK 可能与 Android SDK 存在 jlink 不兼容问题: ``` android { compileOptions { sourceCompatibility = JavaVersion.VERSION_17 targetCompatibility = JavaVersion.VERSION_17 } } ``` #### 5. Gradle 版本兼容性 AGP 9.0+ 需要 Gradle 9.3.1+: ``` # gradle/wrapper/gradle-wrapper.properties distributionUrl=https\://services.gradle.org/distributions/gradle-9.3.1-all.zip ``` ### 调试日志 启用 info 日志以查看插件详细信息: ``` ./gradlew assembleDebug --info | grep -i "anchor\|merkle\|integrity" ``` ## 🖥️ 验证服务器 AnchorPQ Verification Server 是一个生产就绪的 Quarkus 后端,用于在运行时验证应用程序完整性。 ### 使用 Docker 快速开始 ``` # 启动带有 PostgreSQL 的服务器 docker-compose up -d # 服务器位于 http://localhost:8080 # Swagger UI 位于 http://localhost:8080/swagger-ui ``` ### 服务器功能 | 功能 | 描述 | |---------|-------------| | 🔐 **ML-KEM Key Exchange** | 后量子安全通信 | | 🌲 **Merkle Root Verification** | 服务器锚定的完整性验证 | | 🗄️ **PostgreSQL Storage** | 权威完整性记录数据库 | | 📊 **OpenAPI/Swagger** | 交互式 API 文档 | | 🐳 **Docker Ready** | 生产级容器化 | | ⚡ **Rate Limiting** | 基础滥用防护 | ### API 端点 | 端点 | 方法 | 描述 | |----------|--------|-------------| | `/public-key` | GET | 获取 ML-KEM 公钥 | | `/verify` | POST | 验证完整性 (加密) | | `/admin/records` | GET/POST | 管理权威记录 | | `/health` | GET | 健康检查 | ### 服务器架构 ``` ┌─────────────────────────────────────────────────────────────────┐ │ Android Client │ │ 1. Compute Merkle root from APK │ │ 2. Fetch server's ML-KEM public key │ │ 3. Encapsulate shared secret → derive AES key │ │ 4. Encrypt integrity payload with AES-GCM │ │ 5. POST /verify with encrypted request │ └─────────────────────────────────────────────────────────────────┘ │ ▼ ┌─────────────────────────────────────────────────────────────────┐ │ AnchorPQ Server (Quarkus) │ │ 1. ML-KEM decapsulate → recover shared secret │ │ 2. Derive AES key using HKDF-SHA3-256 │ │ 3. Decrypt integrity payload │ │ 4. Compare Merkle root with canonical database record │ │ 5. Return: APPROVED | RESTRICTED | REJECTED │ └─────────────────────────────────────────────────────────────────┘ ``` ### 服务器配置 ``` # 数据库 DB_HOST=localhost DB_PORT=5432 DB_NAME=anchorpq DB_USERNAME=anchorpq DB_PASSWORD=your_secure_password # ML-KEM (CRYSTALS-Kyber) anchorpq.crypto.mlkem.parameter-set=ML-KEM-768 ``` ### CI/CD 集成 在每次构建后注册权威 Merkle roots: ``` # 在构建成功后的 CI pipeline 中 curl -X POST http://your-server:8080/admin/records \ -H "Content-Type: application/json" \ -d '{ "version": "1.0.0", "variant": "release", "merkleRoot": "'$(cat build/integrity/release/merkle-root.txt)'", "signerFingerprint": "your-signer-sha256" }' ``` 📖 **完整文档**:有关完整的服务器文档,请参阅 [anchorpq-server/README.md](SERVER-README.md)。 ## 📋 环境要求 | 要求 | 版本 | |-------------|---------| | Gradle | 9.3.1+ | | Java | 17 | | Android Gradle Plugin | 9.0+ | | Android SDK | API 24+ (minSdk) | | Kotlin | 内置于 AGP 9.0 | ### 服务器要求 | 要求 | 版本 | |-------------|---------| | Java | 17+ | | Docker | 20.10+ (用于容器化部署) | | PostgreSQL | 14+ | ### 依赖项 该插件需要 classpath 上存在以下依赖项: ``` dependencies { classpath("org.bouncycastle:bcprov-jdk18on:1.83") classpath("org.bouncycastle:bcpkix-jdk18on:1.83") classpath("com.google.code.gson:gson:2.13.2") } ``` ## 🧪 运行测试 ``` # 运行所有插件测试 ./gradlew test # 运行特定测试类 ./gradlew test --tests "*MerkleTreeTest*" # 以详细输出模式运行 ./gradlew test --info ``` ### 测试覆盖 | 测试类 | 测试数 | 描述 | |------------|-------|-------------| | MerkleTreeTest | 16 | Merkle 树构建、证明生成/验证 | | HashUtilsTest | 8 | 哈希算法、十六进制转换 | | MLKemHelperTest | 6 | 后量子加密 | | AnchorPQPluginTest | 4 | 插件集成 | ## 📄 许可证 ``` Copyright 2026 Anchor PQ Contributors Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. ``` ## 🤝 贡献 欢迎贡献!请: 1. Fork 本仓库 2. 创建一个功能分支 (`git checkout -b feature/amazing-feature`) 3. 提交您的更改 (`git commit -m 'Add amazing feature'`) 4. 推送到分支 (`git push origin feature/amazing-feature`) 5. 打开一个 Pull Request ## 📞 支持 - **问题反馈**: [GitHub Issues](https://github.com/namanoncode/AndroidPostQuantumIntegrityFramework/issues) - **讨论交流**: [GitHub Discussions](https://github.com/namanoncode/AndroidPostQuantumIntegrityFramework/discussions) - **作者**: [namanoncode](https://github.com/namanoncode) ## 🙏 致谢 - [Bouncy Castle](https://www.bouncycastle.org/) - 后量子密码学实现 - [NIST PQC](https://csrc.nist.gov/projects/post-quantum-cryptography) - ML-KEM 标准化 - Android Open Source Project **用心 ❤️ 打造,为了安全的 Android 开发**
标签:Android, CRYSTALS-Kyber, DSL, Gradle插件, Kotlin, Merkle树, ML-KEM, Quarkus, 后台面板检测, 后量子密码学, 域名枚举, 字节码哈希, 完整性校验, 测试用例, 白盒加密, 目录枚举, 移动安全, 网络安全, 请求拦截, 运行时验证, 量子安全, 防御对抗, 防篡改, 隐私保护