You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中打开加密Realm DB文件时如何指定加密密钥

Flutter 打开加密Realm文件配置方法

Realm 官方包的Configuration.local构造函数原生支持传入加密密钥,直接配置encryptionKey参数即可,注意两个容易踩的前置坑:

  • 加密密钥必须是长度恰好64字节的字节数组,长度不符合会直接抛出参数错误
  • 打包在assets目录下的Realm文件是只读资源,无法直接打开,需要先拷贝到应用可写目录再加载

正确实现代码

import 'dart:io';
import 'dart:typed_data';
import 'package:realm/realm.dart';
import 'package:path_provider/path_provider.dart';
import 'package:flutter/services.dart';

Future<Realm> initEncryptedRealm() async {
  // 替换为你自己的64字节加密密钥
  final Uint8List yourEncryptionKey = Uint8List.fromList(
    // 此处替换为实际加密时使用的64位字节序列
    List.filled(64, 0),
  );

  // 先将assets内的realm文件拷贝到应用可写目录
  final appDir = await getApplicationDocumentsDirectory();
  final targetRealmPath = '${appDir.path}/myfile.realm';
  if (!await File(targetRealmPath).exists()) {
    final realmBytes = await rootBundle.load('assets/myfile.realm');
    await File(targetRealmPath).writeAsBytes(
      realmBytes.buffer.asUint8List(
        realmBytes.offsetInBytes,
        realmBytes.lengthInBytes,
      ),
    );
  }

  // 初始化配置时传入加密密钥
  final config = Configuration.local(
    [Car.schema],
    disableFormatUpgrade: true,
    path: targetRealmPath,
    encryptionKey: yourEncryptionKey,
  );

  return Realm(config);
}

常见报错排查

  • 如果提示解密失败:优先检查传入的密钥和文件加密时使用的密钥是否完全一致,是否存在字节序错误、长度偏差
  • 如果提示权限错误:检查是否直接打开了assets路径下的文件,确认目标文件所在目录有读写权限
  • 如果提示格式不匹配:确认当前使用的Realm SDK版本和生成该realm文件的版本差没有超过兼容范围,disableFormatUpgrade: true会禁止自动升级文件格式,版本跨度太大也会打开失败

内容的提问来源于stack exchange,提问作者user2039804

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.29 14:31:15