selfpass/client/lib/repositories/encrypted_shared_preference...

103 lines
2.5 KiB
Dart

import 'dart:convert';
import 'package:shared_preferences/shared_preferences.dart';
import 'config_base.dart';
import '../types/abstracts.dart';
import '../types/connection_config.dart';
import '../utils/crypto.dart' as crypto;
class EncryptedSharedPreferences extends ConfigBase implements ConfigRepo {
@override
Future<ConnectionConfig> get connectionConfig async {
checkIfPasswordMatched();
final prefs = await SharedPreferences.getInstance();
final cipherText = prefs.getString(ConfigBase.keyConnectionConfig);
if (cipherText == null) return null;
final configJson = crypto.decrypt(cipherText, password);
return ConnectionConfig.fromJson(json.decode(configJson));
}
@override
Future<void> deleteAll() async {
checkIfPasswordMatched();
final prefs = await SharedPreferences.getInstance();
prefs.remove(ConfigBase.keyConnectionConfig);
prefs.remove(ConfigBase.keyPassword);
prefs.remove(ConfigBase.keyPrivateKey);
}
@override
Future<bool> matchesPasswordHash(String password) async {
final prefs = await SharedPreferences.getInstance();
passwordMatched = crypto.matchHashedPassword(
prefs.getString(ConfigBase.keyPassword),
password,
);
if (passwordMatched) this.password = password;
return passwordMatched;
}
@override
Future<bool> get passwordIsSet async {
final prefs = await SharedPreferences.getInstance();
final isSet = prefs.containsKey(ConfigBase.keyPassword);
passwordMatched = !isSet;
return isSet;
}
@override
Future<String> get privateKey async {
checkIfPasswordMatched();
final prefs = await SharedPreferences.getInstance();
final cipherText = prefs.getString(ConfigBase.keyPrivateKey);
return crypto.decrypt(cipherText, password);
}
@override
Future<void> setConnectionConfig(ConnectionConfig config) async {
checkIfPasswordMatched();
final prefs = await SharedPreferences.getInstance();
final configJson = json.encode(config);
prefs.setString(
ConfigBase.keyConnectionConfig,
crypto.encrypt(configJson, password),
);
}
@override
Future<void> setPassword(String password) async {
final prefs = await SharedPreferences.getInstance();
this.password = password;
passwordMatched = true;
prefs.setString(ConfigBase.keyPassword, crypto.hashPassword(password));
}
@override
Future<void> setPrivateKey(String key) async {
final prefs = await SharedPreferences.getInstance();
prefs.setString(ConfigBase.keyPrivateKey, crypto.encrypt(key, password));
}
}