init method
Future
init({
- bool encrypt = true,
- StorageType storageType = StorageType.HIVE,
- String? hiveSubDir,
- String hiveName = "",
Implementation
Future init({
bool encrypt = true,
StorageType storageType = StorageType.HIVE,
String? hiveSubDir,
String hiveName = ""
}) async{
_storageType = storageType;
_encrypt = encrypt;
_hiveName = ObjectUtil.isEmpty(hiveName)? _defHiveName : hiveName;
_prefs = await SharedPreferences.getInstance();
///先获取rsa密钥
if(encrypt){
/**
* 基本加密逻辑
*
* 1.生成一个随机数,使用公钥秘钥进行加密,公钥秘钥使用salsa加密
* 2.使用这个随机数来进行aes加解密
* 3.key使用salsa进行加密混淆
*/
///第一层加密
final key = Key.fromUtf8(defPassword);
final iv = IV.fromLength(8);
final salsaEncrypt = Encrypter(Salsa20(key));
RSAPrivateKey rsaPrivateKey;
RSAPublicKey rsaPublicKey;
late String realRandomKey;
String publicKey;
String privateKey;
String publicPrivateKey;
var aesKey;
if(_prefs.containsKey(_randomKey)){
publicPrivateKey = _prefs.getString(_rsaKey) ?? "";
publicPrivateKey = salsaEncrypt.decrypt64(publicPrivateKey, iv: iv);
publicKey = publicPrivateKey.split(rsaSplit)[0];
privateKey = publicPrivateKey.split(rsaSplit)[1];
rsaPublicKey = RsaUtil.rsaPublicKeyFromPem(publicKey);
rsaPrivateKey = RsaUtil.rsaPrivateKeyFromPem(privateKey);
String encryptRandomKey = _prefs.getString(_randomKey) ?? "";
///解密randomKey
realRandomKey = RsaUtil.rsaDecrypt(encryptRandomKey, rsaPrivateKey);
}else{
///未进行过加密
var pair = RsaUtil.generateRSAKeyPair();
rsaPrivateKey = pair.privateKey as RSAPrivateKey;
rsaPublicKey = pair.publicKey as RSAPublicKey;
privateKey = RsaUtil.encodeRSAPrivateKeyToPem(rsaPrivateKey);
publicKey = RsaUtil.encodeRSAPublicKeyToPem(rsaPublicKey);
///保存到本地,先进行salsa20加密
publicPrivateKey = "$publicKey$rsaSplit$privateKey";
publicPrivateKey = salsaEncrypt.encrypt(publicPrivateKey, iv: iv).base64;
_prefs.setString(_rsaKey, publicPrivateKey);
///保存随机数
realRandomKey = _generatePassword();
String encryptRandomKey = RsaUtil.rsaEncrypt(realRandomKey, rsaPublicKey);
_prefs.setString(_randomKey, encryptRandomKey);
}
aesKey = Key.fromUtf8(realRandomKey);
_realEncrypt = Encrypter(AES(aesKey, mode: AESMode.cbc));
if(_storageType == StorageType.HIVE){
_realEncryptBox = await Hive.openBox(_hiveName, encryptionCipher: HiveAesCipher(base64Url.decode(realRandomKey)));
}
}else{
if(_storageType == StorageType.HIVE){
_realEncryptBox = await Hive.openBox(_hiveName);
}
}
}