1 year ago

#299059

test-img

Jake B.

How can I call an Encrypted Hive Box to a class?

I am needing to encrypt a hive box, in which the box 'user_api' is to be called in Api_Page_() to receive user input to store inside said box. However, the encryptedBox is not defined within the class. The Hive Docs display the encryption code is to be done inside of the main() function, which I have done, but I am unsure of how to take the box outside of main(). Any help or advice is greatly appreciated!

My Code:

import 'dart:convert';
import 'dart:io';
import 'package:flutter/material.dart';
import 'package:flutter_secure_storage/flutter_secure_storage.dart';
import 'package:hive_flutter/hive_flutter.dart';
import 'package:hive/hive.dart';
import 'package:path_provider/path_provider.dart';



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

  // HIVE ENCRYPTION----------------------------------------
  const secureStorage = FlutterSecureStorage();

  final encryptionKey = await secureStorage.read(key: 'key');
  if (encryptionKey == null) {
    final key = Hive.generateSecureKey();
    await secureStorage.write(
      key: 'key',
      value: base64Encode(key),
    );
  }
  final key = await secureStorage.read(key: 'key');
  final encryptKey = base64Url.decode(key);
  print('Encryption key: $encryptKey');
  // HIVE ENCRYPTION----------------------------------------


  // HIVE INIT---------------------------------------------
  Directory directory = await getApplicationDocumentsDirectory();
  Hive.init(directory.path);
  await Hive.initFlutter();
  final encryptedBox = Hive.openBox<String>('user_api', encryptionCipher: HiveAesCipher(encryptKey));     // Initially Opens Box on App Start
  // HIVE INIT---------------------------------------------



  runApp(myApp());
}


class myApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    
    return const MaterialApp(
      debugShowCheckedModeBanner: false,    // Removes Debug Banner. [Delete before app release]
      title: 'App Title Placeholder',
      home: API_Page_()                   // Calls API_Page_ class from api_page.dart
    );
  }
}

class API_Page_ extends StatelessWidget {
  const API_Page_({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: RaisedButton(onPressed: () { var eBox = encryptedBox<String>('user_api');
        },
      )
    );
  }
}

flutter

encryption

hive

box

0 Answers

Your Answer

Accepted video resources