You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Android系统中通过编程方式安装自签名CA证书

Android 程序化安装CA证书实现步骤

一、申请必要权限

  • 若需读取外部存储中的证书,需根据系统版本动态申请对应权限:
    • Android 12及以下:READ_EXTERNAL_STORAGE
    • Android 13及以上:READ_MEDIA_FILES
  • 权限申请代码示例(Kotlin):
private const val REQUEST_STORAGE_PERMISSION = 1001

// 检查并申请权限
fun checkStoragePermission(activity: Activity) {
    val permission = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {
        Manifest.permission.READ_MEDIA_FILES
    } else {
        Manifest.permission.READ_EXTERNAL_STORAGE
    }
    if (ContextCompat.checkSelfPermission(activity, permission) != PackageManager.PERMISSION_GRANTED) {
        ActivityCompat.requestPermissions(activity, arrayOf(permission), REQUEST_STORAGE_PERMISSION)
    }
}

二、准备CA证书文件

方式1:从应用assets目录读取

将.pem或.der格式的CA证书放入src/main/assets目录,复制到应用可访问的外部路径:

fun copyCertFromAssets(context: Context, certFileName: String): String? {
    val outputFile = File(context.getExternalFilesDir(null), certFileName)
    return try {
        context.assets.open(certFileName).use { input ->
            FileOutputStream(outputFile).use { output ->
                input.copyTo(output)
            }
        }
        outputFile.absolutePath
    } catch (e: IOException) {
        e.printStackTrace()
        null
    }
}

方式2:让用户选择存储中的证书

调用系统文件选择器获取证书Uri,再根据Scoped Storage规则处理文件路径。

三、调用系统证书安装界面

使用系统Intent启动CA证书安装流程,需通过FileProvider生成安全Uri避免文件暴露异常:

fun startCertInstall(context: Context, certPath: String, certName: String = "自定义CA证书") {
    val certFile = File(certPath)
    val uri = FileProvider.getUriForFile(
        context,
        "${context.packageName}.fileprovider",
        certFile
    )

    val installIntent = Intent("android.intent.action.INSTALL_CERTIFICATE").apply {
        putExtra("android.intent.extra.CERTIFICATE", uri)
        putExtra("android.intent.extra.NAME", certName)
        addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
        addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)
    }

    context.startActivity(installIntent)
}

四、配置FileProvider

  1. 在AndroidManifest.xml中注册FileProvider:
<provider
    android:name="androidx.core.content.FileProvider"
    android:authorities="${applicationId}.fileprovider"
    android:exported="false"
    android:grantUriPermissions="true">
    <meta-data
        android:name="android.support.FILE_PROVIDER_PATHS"
        android:resource="@xml/file_paths" />
</provider>
  1. 在res/xml目录创建file_paths.xml,定义可共享的文件路径:
<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <external-files-path name="external_files" path="." />
</paths>

五、流程衔接

  • 在onRequestPermissionsResult中处理权限申请结果,权限通过后执行证书复制和安装操作。
  • 启动安装Intent后,系统会引导用户完成证书信任设置(如选择证书用途、确认信任),无需应用额外处理。

内容的提问来源于stack exchange,提问作者Mike

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 14:06:15