0

对于许多有经验的开发人员来说,这可能是一个愚蠢而多余的问题,但是我没有经验,所以我提出了这个问题。我想访问此框中的加密值,以直观地手动验证并观察加密是否已完成。我似乎无法打印加密的值,只有解密的值出来。

我正在用一些演示代码测试这个例子。

我做错了什么还是 .get() 方法默认在通话时解密?

import 'dart:convert';
import 'package:flutter/cupertino.dart';
import 'package:hive/hive.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive_flutter/hive_flutter.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Hive.initFlutter();

  String key = 'key';
  String secret = 'secret value';

  final FlutterSecureStorage secureStorage = const FlutterSecureStorage();
  var containsEncryptionKey = await secureStorage.containsKey(key: 'key');
  if (!containsEncryptionKey) {
    var key = Hive.generateSecureKey();
    await secureStorage.write(key: 'key', value: base64UrlEncode(key));
  }

  print(await secureStorage.readAll());

  var encryptionKey = base64Url.decode(await secureStorage.read(key: 'key'));
  print('Encryption key: $encryptionKey');

  var encryptedBox = await Hive.openBox('secure_box',
      encryptionCipher: HiveAesCipher(encryptionKey));
  encryptedBox.put(key, secret);

  print(Hive.box('secure_box').values);     // Should this not be encrypted text?
  print(encryptedBox.get(key));
}

输出:

flutter: {key: Wr1fM3XHtIefLX8JKGJfPNiHdaWiNZspbml6NJeJkTk=}
flutter: Encryption key: [90, 189, 95, 51, 117, 199, 180, 135, 159, 45, 127, 9, 40, 98, 95, 60, 216, 135, 117, 165, 162, 53, 155, 41, 110, 105, 122, 52, 151, 137, 145, 57]
flutter: (secret value, secret_value)
flutter: secret_value
4

1 回答 1

1

因为当你调用Hive.box('secure_box').values
它实际上返回一个以前打开的框,也就是encryptedBoxHiveAesCipher(encryptionKey)这就是为什么你可以看到正确的值
你可以在这里参考源代码描述https://github.com/hivedb/hive/blob/59ad5403593283233d922f62f76832c64fa33a3b/hive/lib/src /hive.dart#L39

/// Returns a previously opened box.
  Box<E> box<E>(String name);

To open an existing box, you need to provide the key you used to create it
Encrypted box - Why store the encryption key? 您可以在https://github.com/hivedb/hive/issues/556#issuecomment-770458818 中参考 hive 团队的评论
因此,如果您打开正确的框,您将始终获得正确的纯文本值HiveAesCipher(encryptionKey)

于 2021-02-22T01:49:26.093 回答