我有一个要求,其中字符串将从flutter网络应用程序使用dart 加密.加密后的字符串将被发送到服务器,iOS Swift也会使用.
DART文件文件
String encryptString(Uint8List key) {
try {
final encryptionKey = Key(key);
final iv = IV.fromLength(16); // 16 bytes IV for AES-GCM
final macValue = utf8.encode("");
final encrypter = Encrypter(AES(encryptionKey, mode: AESMode.gcm));
final encrypted = encrypter.encrypt(
this,
iv: iv,
associatedData: macValue,
);
final concatenatedBytes = Uint8List.fromList([...iv.bytes, ...encrypted.bytes, ...macValue]);
final base64Encoded = base64.encode(concatenatedBytes);
return base64Encoded;
} catch (e) {
print('Error while encrypting: $e');
return '';
}
}
然而,加密文本我无法在Swift中解密.我总是得到CryptoKit.CryptoKit错误.身份验证失败
swift代码
func decrypt(withKey key: SymmetricKey) throws -> String {
guard let encryptedData = Data(base64Encoded: self) else { throw EncryptionError.invalidData }
// Open the sealed box using the encryption key
do {
let sealedBox = try AES.GCM.SealedBox(combined: encryptedData)
// Decrypt the data
let decryptedData = try AES.GCM.open(sealedBox, using: key)
// Convert decrypted data to string
guard let decryptedString = String(data: decryptedData, encoding: .utf8) else {
throw EncryptionError.decryptionFailed
}
return decryptedString
} catch {
print(error.localizedDescription)
throw EncryptionError.invalidData
}
}
我试过上面的片段.似乎不起作用,请帮忙:)