草庐IT

Android Realm 加密示例

coder 2023-12-09 原文

我已经从以下链接创建了 Realm Encryption Example 项目源 https://github.com/realm/realm-java/tree/master/examples/encryptionExample/src/main/java/io/realm/examples/encryptionexample .当我在没有任何代码更改的情况下运行该项目时,它运行时没有错误。但是我在源代码中注释了以下行

Realm.deleteRealm(realmConfiguration);

因为不需要为我删除旧文件。 然后我启动应用程序。它抛出错误 java.lang.IllegalArgumentException:非法参数: Realm 文件格式无效。

如何读取具有相同加密 key 的 Realm 文件。

源代码:

    package io.realm.examples.encryptionexample;

import android.app.Activity;
import android.os.Bundle;
import android.util.Log;

import java.security.SecureRandom;

import io.realm.Realm;
import io.realm.RealmConfiguration;

public class EncryptionExampleActivity extends Activity {

    public static final String TAG = EncryptionExampleActivity.class.getName();

    private Realm realm;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        // Generate a key
        // IMPORTANT! This is a silly way to generate a key. It is also never stored.
        // For proper key handling please consult:
        // * https://developer.android.com/training/articles/keystore.html
        // * http://nelenkov.blogspot.dk/2012/05/storing-application-secrets-in-androids.html
        byte[] key = new byte[64];
        new SecureRandom().nextBytes(key);
        RealmConfiguration realmConfiguration = new RealmConfiguration.Builder(this)
                .encryptionKey(key)
                .build();

        // Start with a clean slate every time
        Realm.deleteRealm(realmConfiguration);

        // Open the Realm with encryption enabled
        realm = Realm.getInstance(realmConfiguration);

        // Everything continues to work as normal except for that the file is encrypted on disk
        realm.beginTransaction();
        Person person = realm.createObject(Person.class);
        person.setName("Happy Person");
        person.setAge(14);
        realm.commitTransaction();

        person = realm.where(Person.class).findFirst();
        Log.i(TAG, String.format("Person name: %s", person.getName()));
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        realm.close(); // Remember to close Realm when done.
    }
}

提前致谢。

最佳答案

我遇到了同样的问题。只需像这样更改文件的名称:

RealmConfiguration config = new RealmConfiguration.Builder(getActivity().getBaseContext())
            .name("myrealm_designtv.realm")
            .encryptionKey(loadkeyStore())
            .build();
Realm.setDefaultConfiguration(config);

并且还要更改您的加密 key ,这不是正确的方法。使用 keystore 。这是我使用的教程 http://www.androidauthority.com/use-android-keystore-store-passwords-sensitive-information-623779/ 如果您需要更多帮助,我可以为您提供我的 loadkeyStore() 函数(我没有这样做,因为这不是这里的问题)。

////////////////这是我的 laodKeyStore 函数///////////

public byte[] loadkey(Context context) {


    byte[] content = new byte[64];
    try {
        if (ks == null) {
            createNewKeys(context);
        }

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

         content= ks.getCertificate(ALIAS).getEncoded();
        Log.e(TAG, "key original :" + Arrays.toString(content));
    } catch (KeyStoreException | CertificateException | IOException | NoSuchAlgorithmException e) {
        e.printStackTrace();
    }
    content = Arrays.copyOfRange(content, 0, 64);
    return content;
}

/* 你也需要 createNewKeys 函数 */

public void createNewKeys(Context context) throws KeyStoreException {

    firstloadKeyStore();
    try {
        // Create new key if needed
        if (!ks.containsAlias(ALIAS)) {
            Calendar start = Calendar.getInstance();
            Calendar end = Calendar.getInstance();
            end.add(Calendar.YEAR, 1);
            KeyPairGeneratorSpec spec = new KeyPairGeneratorSpec.Builder(context)
                    .setAlias(ALIAS)
                    .setSubject(new X500Principal("CN=Sample Name, O=Android Authority"))
                    .setSerialNumber(BigInteger.ONE)
                    .setStartDate(start.getTime())
                    .setEndDate(end.getTime())
                    .build();
            KeyPairGenerator generator = KeyPairGenerator.getInstance("RSA", "AndroidKeyStore");
            generator.initialize(spec);

            KeyPair keyPair = generator.generateKeyPair();
            Log.e(TAG, "key :" + keyPair.getPrivate().getEncoded().toString());

        }
    } catch (Exception e) {
        Log.e(TAG, Log.getStackTraceString(e));
    }
}

关于Android Realm 加密示例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31338553/

有关Android Realm 加密示例的更多相关文章

  1. postman——集合——执行集合——测试脚本——pm对象简单示例02 - 2

    //1.验证返回状态码是否是200pm.test("Statuscodeis200",function(){pm.response.to.have.status(200);});//2.验证返回body内是否含有某个值pm.test("Bodymatchesstring",function(){pm.expect(pm.response.text()).to.include("string_you_want_to_search");});//3.验证某个返回值是否是100pm.test("Yourtestname",function(){varjsonData=pm.response.json

  2. ruby - 使用 AES 的 Rails 加密,过于复杂 - 2

    我在加密来self正在使用的第三方供应商的值时遇到问题。他们的指令如下:1)Converttheencryptionpasswordtoabytearray.2)Convertthevaluetobeencryptedtoabytearray.3)Theentirelengthofthearrayisinsertedasthefirstfourbytesontothefrontofthefirstblockoftheresultantbytearraybeforeencryption.4)EncryptthevalueusingAESwith:1.256-bitkeysize,2.25

  3. Ruby-vips 图像处理库。有什么好的使用示例吗? - 2

    我对图像处理完全陌生。我对JPEG内部是什么以及它是如何工作一无所知。我想知道,是否可以在某处找到执行以下简单操作的ruby​​代码:打开jpeg文件。遍历每个像素并将其颜色设置为fx绿色。将结果写入另一个文件。我对如何使用ruby​​-vips库实现这一点特别感兴趣https://github.com/ender672/ruby-vips我的目标-学习如何使用ruby​​-vips执行基本的图像处理操作(Gamma校正、亮度、色调……)任何指向比“helloworld”更复杂的工作示例的链接——比如ruby​​-vips的github页面上的链接,我们将不胜感激!如果有ruby​​-

  4. arrays - 如何在下面的示例中将两个值数组分组为 n 个值数组? - 2

    我已经有很多两个值数组,例如下面的例子ary=[[1,2],[2,3],[1,3],[4,5],[5,6],[4,7],[7,8],[4,8]]我想把它们分组到[1,2,3],[4,5],[5,6],[4,7,8]因为意思是1和2有关系,2和3有关系,1和3有关系,所以1,2,3都有关系我如何通过ruby​​库或任何算法来做到这一点? 最佳答案 这是基本Bron–Kerboschalgorithm的Ruby实现:classGraphdefinitialize(edges)@edges=edgesenddeffind_maximum_

  5. ruby - Google-api-ruby-client 翻译 API 示例 - 2

    很高兴看到google代码:google-api-ruby-client项目,因为这对我来说意味着Ruby人员可以使用GoogleAPI-s来完善代码。虽然我现在很困惑,因为给出的唯一示例使用Buzz,并且根据我的实验,Google翻译(v2)api的行为必须与google-api-ruby-client中的Buzz完全不同。.我对“Explorer”演示示例很感兴趣——但据我所知,它并不是一个探索器。它所做的只是调用一个Buzz服务,然后浏览它已经知道的关于Buzz服务的事情。对我来说,Explorer应该让您“发现”所公开的服务和方法/功能,而不一定已经知道它们。我很想听听使用这个

  6. ruby - 如何使用私钥加密完全加密 Ruby 中的数据? - 2

    首先,关于我们系统的一些信息,它基本上是建筑行业的电子招标解决方案。所以:列表项我们的系统有多家公司每个公司都有多个用户每家公司可以创建多个拍卖然后其他公司可以为可用的拍卖提交他们的出价。一个出价包含数百或数千个单独的项目,我们只需要加密这些记录的“价格”部分。我们面临的问题是,我们的大客户不希望我们知道投标价格,至少在投标过程中是这样,这是完全可以理解的。现在,我们只是通过对称加密对价格进行加密,因此即使价格在数据库中有效加密,他们担心的是我们拥有解密价格的key。因此,我们正在研究某种形式的公钥加密系统。以下是我们对解决方案的初步想法:当一家公司注册时,我们会使用OpenSSL为其

  7. ruby-on-rails - 我如何比较 'Bcrypt' Gem解密的密码和加密的密码 - 2

    我正在尝试对某些帖子的评论使用简单的身份验证。用户使用即时ID和密码输入评论我使用“bcrypt”gem将密码存储在数据库中。在comments_controller.rb中像这样@comment=Comment.new(comment_params)bcrypted_pwd=BCrypt::Password.create(@comment.user_pwd)@comment.user_pwd=bcrypted_pwd当用户想要删除他们的评论时,我使用data-confirm-modalgem来确认数据在这部分,我必须解密用户输入的密码以与数据库中的加密密码进行比较我怎样才能解密密码,

  8. ruby - 是否有 SproutCore 或 Cappuccino 的现场演示/示例应用程序 - 2

    在他们的网站上找不到任何内容。我主要只是想看看哪个值得一试(当然是RIA)。谢谢 最佳答案 SproutCoredemos 关于ruby-是否有SproutCore或Cappuccino的现场演示/示例应用程序,我们在StackOverflow上找到一个类似的问题: https://stackoverflow.com/questions/1419788/

  9. ruby - 如何在Elixir中使用AES CBC 128进行加密和解密 - 2

    我在Rails中有一个具有以下方法的应用程序,该方法可以加密和解密文本并与Java客户端通信。defencrypt(string,key)cipher=OpenSSL::Cipher::AES.new(128,:CBC)cipher.encryptcipher.padding=1cipher.key=hex_to_bin(Digest::SHA1.hexdigest(key)[0..32])cipher_text=cipher.update(string)cipher_textexcenddefhex_to_bin(str)[str].pack"H*"enddefbin_to_hex(

  10. ruby - 如何设置自动测试以仅重新运行失败的 rspec 示例 - 2

    我对自动测试的工作方式的印象(基于cucumbergithubwiki和其他在线内容)是它应该重新运行红色示例,直到它们通过。我的问题是它会重新运行规范文件中找到失败示例的所有示例,包括通过的示例。我不想浪费时间在修复失败示例的同时重新运行通过的示例。是否可以配置自动测试以便仅运行失败的示例? 最佳答案 您需要rspec-retrygem。以下是文档中有关如何实现它的一些示例:将它应用到覆盖整个测试套件的configureblock中...RSpec.configuredo|config|config.verbose_retry=t

随机推荐