Ad

Verifying Encryption Of Hive SecuredBox In Flutter

- 1 answer

This is probably a dumb and redundant question to many experienced devs, however I'm not experienced and so I pose this question. I would like to access the encrypted value in this box to visually, manually verify and observe that encryption has been accomplished. I don't seem to be able to print the encrypted value, only the deciphered value comes out.

I'm testing this example with some demo code.

Am I doing something wrong or is the .get() method deciphering on call by default?

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));
}

Output:

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
Ad

Answer

Because when you call Hive.box('secure_box').values
It actually return a previously opened box, aka encryptedBox with HiveAesCipher(encryptionKey) , that's why you can see correct value
You can reference source code description here 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
You can reference hive teams's comments in Encrypted box - Why store the encryption key?https://github.com/hivedb/hive/issues/556#issuecomment-770458818
So you will always get correct plaintext value if you open box with correct HiveAesCipher(encryptionKey)

Ad
source: stackoverflow.com
Ad