import 'dart:typed_data'; import 'package:encrypt/encrypt.dart'; class AESData { final List iv; final List data; AESData({required this.iv, required this.data}); } class AESCipher { final Uint8List _aesKey; AESCipher._(this._aesKey); static Future 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 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 decrypt(AESData data) async { final iv = IV(Uint8List.fromList(data.iv)); return _aesDecrypt(Uint8List.fromList(data.data), _aesKey, iv); } static Future _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 _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); } }