1. Keystore 机制与 RSA 密钥体系

1.1 Android KeyStore 架构

Android KeyStore 是一个硬件/软件协同的密钥安全容器,从 Android 4.3(API 18)引入,在 Android 6.0+ 中获得 TEE(Trusted Execution Environment)强力支持。其核心设计原则是 密钥永不离开安全边界——密钥材料可以在受硬件保护的区域(如 StrongBox、TEE)生成和使用,应用只能通过 KeyStore 服务间接调用加密操作,无法直接读取明文密钥。

关键术语
KeyStore Provider:AndroidKeyStore 是标准的 Java Cryptography Architecture (JCA) Provider。
KeyStore.Entry:代表一个存储的密钥,支持 PrivateKeyEntry、SecretKeyEntry、TrustedCertificateEntry。
KeyGenParameterSpec:生成密钥时使用的规格,控制算法、用途、访问限制等。

1.2 RSA 算法特性

RSA 是非对称加密算法,基于大整数因子分解难题。在 Android KeyStore 中使用 RSA 时需关注以下特性:

特性说明Android KeyStore 限制
密钥长度常用 2048 / 4096 位最小 512 位(不推荐),推荐 2048 位以上
填充模式RSA/ECB/PKCS1Padding、RSA/ECB/OAEPPaddingOAEP 推荐使用 SHA-256 或 SHA-384
签名算法SHA256withRSA、SHA384withRSA 等需与密钥用途匹配
加密/解密私钥解密、公钥加密KeyStore 内部执行,应用只得到结果
填充安全警告
避免使用 RSA/ECB/PKCS1Padding 做加密(存在 Bleichenbacher 攻击风险),推荐使用 RSA/ECB/OAEPWithSHA-256AndMGF1Padding。KeyStore 生成密钥时通过 setEncryptionPaddings() 指定填充。

1.3 密钥用途分类

Android KeyStore 通过 KeyGenParameterSpec.Builder 的 setPurposes() 方法明确密钥用途,同一 RSA 密钥对可组合多种用途:

  • 加密/解密 (PURPOSE_ENCRYPT / PURPOSE_DECRYPT):公钥加密,私钥解密。
  • 签名/验证 (PURPOSE_SIGN / PURPOSE_VERIFY):私钥签名,公钥验签。
  • 密钥协商 (PURPOSE_AGREE_KEY):RSA 通常不用于协商,但可通过密钥交换协议间接实现。

1.4 Android KeyStore 架构概览

下图展示了应用层、KeyStore 服务、TEE/StrongBox 之间的分层关系:

Android KeyStore 分层架构 用户空间(应用层) APP → javax.crypto.KeyStore.getInstance("AndroidKeyStore") KeyStore 服务(系统进程) 密钥管理、访问控制、认证策略 TEE / StrongBox(可信执行环境) 密钥生成、加密/解密、签名运算(硬件隔离) 安全核心 私钥永远只存在于 TEE/StrongBox 内部,应用和系统进程均无法直接获取

1.5 密钥生成规格示例

创建一个用于 RSA 签名和加密的密钥对(2048位,OAEP填充,需用户认证):

KeyGenParameterSpec spec = new KeyGenParameterSpec.Builder(
        "my_rsa_key",
        KeyProperties.PURPOSE_SIGN | KeyProperties.PURPOSE_VERIFY |
        KeyProperties.PURPOSE_ENCRYPT | KeyProperties.PURPOSE_DECRYPT)
    .setKeySize(2048)
    .setSignaturePaddings(KeyProperties.SIGNATURE_PADDING_RSA_PKCS1)
    .setEncryptionPaddings(KeyProperties.ENCRYPTION_PADDING_RSA_OAEP)
    .setDigests(KeyProperties.DIGEST_SHA256, KeyProperties.DIGEST_SHA384)
    .setUserAuthenticationRequired(true)
    .build();

KeyPairGenerator generator = KeyPairGenerator.getInstance(
        KeyProperties.KEY_ALGORITHM_RSA, "AndroidKeyStore");
generator.initialize(spec);
KeyPair keyPair = generator.generateKeyPair();
要点总结
  • Android KeyStore 提供硬件隔离的密钥存储,私钥无法被导出。
  • RSA 密钥长度推荐 2048 位以上,填充优先使用 OAEP。
  • 通过 KeyGenParameterSpec 精确控制密钥用途,避免过度授权。
  • TEE/StrongBox 是 Android 强安全模型的核心依赖。