如何将使用 SQLCipher 的 SQLite/Room 数据库保存到文件流中?

问题描述

我刚刚学会了如何使用 sqlCipher here,我希望能够将它保存到 sqlite 文件中,但我偶然发现了 this approach where the file is saved via FileOutputStream。但是,FileOutputStream 方法仅在数据库文件未加密时有效。有没有可以推荐的解决方法

如果不是,我的最终目标实际上是:

  1. 使用 Room 创建加密数据库
  2. 为此数据库创建加密备份
  3. 用户能够通过 Google 云端硬盘、电子邮件或其他方式发送此文件,以便在他们需要我查看数据库内容时我也可以查看它
  4. 使这个过程尽可能无缝、隐形,但也尽可能优雅

非常感谢!

这是我尝试做的,它几乎是我上面提到的那两个链接的复制粘贴:

对于数据库

public abstract class MyDatabase extends RoomDatabase {
    public static MyDatabase myDatabase;
    
    // based on https://github.com/sqlcipher/android-database-sqlcipher
    public static synchronized MyDatabase getInstance(Context context) {
        if (MyDatabase == null) {
            final byte[] passphrase = sqliteDatabase.getBytes("userEnteredPassphrase".tochararray());
            final SupportFactory factory = new SupportFactory(passphrase);
            MyDatabase = Room.databaseBuilder(context.getApplicationContext(),MyDatabase.class,"my_database")
                    .addCallback(roomCallback)
                    .openHelperFactory(factory) // WHEN I REMOVE THIS LINE,THE ENTIRE DATABASE GETS SAVED AS A FILE INCLUDING THE TABLES,BUT WHEN THIS LINE IS ACTIVE,THE FILE IS REDUCED TO ABOUT 4kb WITH nothing IN IT
                    .build();
        }
        return MyDatabase;
    }
}

我如何尝试使用 FileOutputStream 保存数据库

public void saveDatabasetoFileOutputStream() {
    File dbfile = this.getDatabasePath("my_database");
    File sdir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_DOWNLOADS),"DBsaves");
    String sfpath = sdir.getPath() + File.separator + "DBsave" + String.valueOf(System.currentTimeMillis());
    
    if (!sdir.exists()) {
        sdir.mkdirs();
    }
    
    File savefile = new File(sfpath);
    
    try {
        savefile.createNewFile();
        
        int buffersize = 8 * 1024;
        byte[] buffer = new byte[buffersize];
        int bytes_read = buffersize;
        
        OutputStream savedb = new FileOutputStream(sfpath);
        InputStream indb = new FileInputStream(dbfile);
        
        while ((bytes_read = indb.read(buffer,buffersize)) > 0) {
            savedb.write(buffer,bytes_read);
        }

        savedb.flush();
        indb.close();
        savedb.close();
    } catch (Exception e) {
        e.printstacktrace();
    }
}

The difference in saved file when the database is ciphered and not ciphered

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...