decrypt static method
将收到的数据进行解密,采用随机生成iv和key的AES解密算法(CBC、Pkcs7)
data
要解密的数据pwd
解密的密码
Implementation
static EasyPacket? decrypt(dynamic data, String? pwd) {
try {
if (pwd != null) {
final hmacSha256 = Hmac(sha256, utf8.encode(pwd)); // HMAC-SHA256
Uint8List bytes;
if (data is String) {
bytes = base64Decode(data);
} else if (data is ByteBuffer) {
bytes = data.asUint8List(); //Web is NativeByteBuffer
} else if (data is Uint8List) {
bytes = data; //Native is Uint8List
} else {
return null;
}
final salt = bytes.sublist(0, 16);
final iv = bytes.sublist(16, 32);
final key = Uint8List.fromList(hmacSha256.convert(salt).bytes);
final body = bytes.sublist(32);
final aesCrypto = Encrypter(AES(Key(key), mode: AESMode.cbc, padding: 'PKCS7'));
final decRes = aesCrypto.decrypt(Encrypted(body), iv: IV(iv));
return EasyPacket.fromJson(jsonDecode(decRes));
} else {
return EasyPacket.fromJson(jsonDecode(data is String ? data : String.fromCharCodes(data)));
}
} catch (error) {
return null;
}
}