Line data Source code
1 : import 'package:encrypt/encrypt.dart';
2 : import 'package:flutter_secure_storage/flutter_secure_storage.dart';
3 :
4 : const _keyLength = 32;
5 : const _ivLength = 16;
6 :
7 : /// Ciper storage
8 : class CipherStorage {
9 : /// Create a new cipher storage
10 4 : CipherStorage();
11 :
12 : static const String _keyKey = 'cipher_storage_key';
13 : static const String _ivKey = 'cipher_storage_iv';
14 : late FlutterSecureStorage _storage;
15 : late final Key _key;
16 : late final IV _iv;
17 :
18 : /// Init ciper storage
19 4 : Future<void> init() async {
20 12 : _storage = FlutterSecureStorage(aOptions: _getAndroidOptions());
21 :
22 8 : final rows = await _storage.readAll();
23 4 : final key = rows[_keyKey];
24 4 : final iv = rows[_ivKey];
25 :
26 : if (key != null && iv != null) {
27 6 : _key = keyFromBase64(key);
28 6 : _iv = ivFromBase64(iv);
29 :
30 : return;
31 : }
32 :
33 : if ((key == null && iv != null) || (key != null && iv == null)) {
34 2 : throw StateError(
35 : 'key and iv reading error: one of them is null while another is not',
36 : );
37 : }
38 :
39 8 : _key = keyFromSecureRandom();
40 8 : _iv = ivFromSecureRandom();
41 :
42 16 : await _storage.write(key: _keyKey, value: _key.base64);
43 16 : await _storage.write(key: _ivKey, value: _iv.base64);
44 : }
45 :
46 : /// Get key
47 8 : Key get key => _key;
48 :
49 : /// Get initialization vector
50 8 : IV get iv => _iv;
51 :
52 4 : AndroidOptions _getAndroidOptions() => AndroidOptions.defaultOptions;
53 :
54 : /// Generate key from base64
55 6 : static Key keyFromBase64(String key) => Key.fromBase64(key);
56 :
57 : /// Generate initialization vector from base64
58 8 : static IV ivFromBase64(String iv) => IV.fromBase64(iv);
59 :
60 : /// Generate a new key
61 8 : static Key keyFromSecureRandom() => Key.fromSecureRandom(_keyLength);
62 :
63 : /// Generate a new initialization vector
64 8 : static IV ivFromSecureRandom() => IV.fromSecureRandom(_ivLength);
65 : }
|