realm版本是4.3.1。
加密代码如下:
private fun initRealm(){
val realmConfig: RealmConfiguration = RealmConfiguration.Builder()
.name("myrealm.realm")//名称
.directory(file)//另存到指定路径
.encryptionKey(getKey())//设置密码
.schemaVersion(1)//设置版本
.deleteRealmIfMigrationNeeded()
.build()
Realm.setDefaultConfiguration(realmConfig)
}
/*
* 64 bits
* @return
*/
private fun getKey(): ByteArray {
return byteArrayOf(0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3,
4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1, 0,
1, 2, 3, 4, 3, 2, 1, 0, 1, 2, 3, 4, 3, 2, 1);
}
密码是用https://github.com/realm/realm-java/blob/master/examples/encryptionExample/src/main/java/io/realm/examples/encryption/Util.java
给出的方法生成的128位的key。
用该key解密后,错误如图所示。估计是获取key的方法不对,请问怎么生存key?
byte[] key = new byte[64];
new SecureRandom().nextBytes(key);
realm文件需要你传递的是一个随机加密的64字节key。(The Realm file can be encrypted on disk by passing a 512-bit encryption key (64 bytes) )
你传递的不是这样的key,你需要按上面的java代码写一个kotlin的实现
如果你需要使用Realm studio打开一个加密数据库,它会提示你输入256位的hex的字符串,这个字符的生成方法如下,这个也是官方例子里提供的代码
public static String bytesToHex(byte[] bytes) {
char[] hexChars = new char[bytes.length * 2];
for ( int j = 0; j < bytes.length; j++ ) {
int v = bytes[j] & 0xFF;
hexChars[j * 2] = hexArray[v >>> 4];
hexChars[j * 2 + 1] = hexArray[v & 0x0F];
}
return new String(hexChars);
}