android - 使用存储在 KeyStore 中的 key 加密 Realm

标签 android encryption realm

我正在尝试在我的应用程序中设置一个加密的默认 Realm 实例。 这个想法是使用具有给定别名的 KeyPairGenerator 生成一个 key ,将其存储在 AndroidKeyStore 中,并在每次需要时使用该 key 。

我做什么

这就是我生成 key 的方式:

  KeyStore ks = KeyStore.getInstance("AndroidKeyStore");
        ks.load(null);

        if (!ks.containsAlias(KEY_ALIAS)) {

            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 99);

            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(this)
                    .setAlias(KEY_ALIAS)
                    .setSubject(new X500Principal("CN=Example, O=ExampleOrg"))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();

            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            generator.initialize(spec);

            KeyPair keyPair = generator.generateKeyPair();
        }

我正在使用 KeyPairGenerator,因为我需要支持 18 及更高版本的 API。

这是我在应用程序中设置默认 Realm 实例的方法:

 RealmConfiguration config = null;
    try {
        config = new RealmConfiguration
                .Builder(this)
                .encryptionKey(ks.getKey(KEY_ALIAS, null).getEncoded())
                .name("dealmatrix.realm")
                .schemaVersion(1)
                .build();

其中 ks 是这样获取的 Keystore 实例:

Keystore ks = KeyStore.getInstance("AndroidKeyStore");
ks.load(null);

出了什么问题

我的问题是这个表达式:

ks.getKey(KEY_ALIAS, null).getEncoded()

返回 null,这会导致异常,这是可以理解的。

我在网上看到这是 KeyStore 系统的预期行为。

如果我确实无法获得存储的加密 key 的字节数组,我应该如何使用所述 key 加密我的 Realm ?

是否有任何其他方法可以安全地存储加密 key ,以便我可以在我的 Realm 配置中使用它?

最佳答案

Realm 仓库的 feature/example/store_password 分支中有一个 WIP 示例项目,它使用了 Android keystore。

https://github.com/realm/realm-java/tree/feature/example/store_password/examples/StoreEncryptionPassword

核心逻辑写在Store.java

在发布这个示例项目之前,我们需要做更多的工作(清理、添加评论、支持旧设备)。但我认为这个项目对你有帮助。

关于android - 使用存储在 KeyStore 中的 key 加密 Realm,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36505418/

相关文章:

javascript - 加密和解密最初是 JSON 的对象

Android通知,当有多个通知时只加载最新的 Intent

android - 通过 Firebase Cloud Messaging 向 Android 设备发送消息

android - 为 TextView 的一部分设置不同的字体和颜色

android - 设置ListView在android中 "item edited"位置右显示

java - Android 字符编码与 Java 字符编码

Python加密函数和全局变量

ios - Realm 持久化的设计模式

ios - 带有单元格的 UITableView 部分

ios - Realm 检索特定数据