55 lines
1.5 KiB
Dart
55 lines
1.5 KiB
Dart
import 'dart:typed_data';
|
|
|
|
import 'package:encrypt/encrypt.dart';
|
|
|
|
class AESData {
|
|
final List<int> iv;
|
|
final List<int> data;
|
|
|
|
AESData({required this.iv, required this.data});
|
|
}
|
|
|
|
class AESCipher {
|
|
final Uint8List _aesKey;
|
|
|
|
AESCipher._(this._aesKey);
|
|
|
|
static Future<AESCipher> generate({int aesKeySize = 256}) async {
|
|
return AESCipher._(Key.fromLength(aesKeySize ~/ 8).bytes);
|
|
}
|
|
|
|
static AESCipher useKey(Uint8List key) {
|
|
return AESCipher._(key);
|
|
}
|
|
|
|
Uint8List getKey() {
|
|
return Uint8List.fromList(_aesKey);
|
|
}
|
|
|
|
Future<AESData> encrypt(Uint8List data) async {
|
|
final iv = IV.fromLength(16); // Generate a random 16-byte IV
|
|
final encryptedData = await _aesEncrypt(data, _aesKey, iv);
|
|
|
|
return AESData(iv: iv.bytes.toList(), data: encryptedData.toList());
|
|
}
|
|
|
|
Future<Uint8List> decrypt(AESData data) async {
|
|
final iv = IV(Uint8List.fromList(data.iv));
|
|
return _aesDecrypt(Uint8List.fromList(data.data), _aesKey, iv);
|
|
}
|
|
|
|
static Future<Uint8List> _aesEncrypt(
|
|
Uint8List data, Uint8List key, IV iv) async {
|
|
var aes = Encrypter(AES(Key(key), mode: AESMode.cbc));
|
|
|
|
final encrypted = await aes.encryptBytes(data.toList(), iv: iv);
|
|
return encrypted.bytes;
|
|
}
|
|
|
|
static Future<Uint8List> _aesDecrypt(
|
|
Uint8List data, Uint8List key, IV iv) async {
|
|
final aes = Encrypter(AES(Key(key), mode: AESMode.cbc));
|
|
final decrypted = await aes.decryptBytes(Encrypted(data), iv: iv);
|
|
return Uint8List.fromList(decrypted);
|
|
}
|
|
}
|