AES-CBC:在React Native中使用CryptoJS,在Swift中使用CryptSwift



我正在构建一个React Native应用程序,该应用程序在iOS上使用NotificationServiceExtension拦截加密通知并在向用户显示之前对其进行解密。

在react原生端,我使用CryptoJS:加密消息

const originalText = 'This will be encrypted';
const theAESKeyWordArray = CryptoJS.enc.Hex.parse("000102030405060708090a0b0c0d0e0f");
const iv = CryptoJS.enc.Hex.parse("101112131415161718191a1b1c1d1e1f"); // Test iv text is in hexadecimal and converting it to wordArray

const ciphertext = CryptoJS.AES.encrypt(originalText, theAESKeyWordArray, {
mode: CryptoJS.mode.CBC,
padding: CryptoJS.pad.Pkcs7,
iv: iv
}).toString();

在使用CryptoSwift的NotificationServiceExtension端(Swift(,在收到通知后,我试图使用以下代码对其进行解码:

";encryptedBody";当输出到控制台时,变量看起来与react本机端的console.log(密文(完全相同。我还可以看到,当打印出clearAESKey.string(编码:.utf8(时,它与我过去在react本机端加密它的方法相同。

let AESKey = Array<UInt8>(hex: try clearAESKey.string(encoding: .utf8))
let iv =  Array<UInt8>(hex: "101112131415161718191a1b1c1d1e1f")
let bufContent: [UInt8] = [UInt8] (encryptedBody.utf8)
let aes = try AES(key: AESKey, blockMode: CBC(iv: iv), padding: .pkcs7) 
let padded = Padding.pkcs7.add(to: bufContent, blockSize: AES.blockSize)

let decryptedBody = try aes.decrypt(padded)  
let decryptedData = Data(decryptedBody)
let decryptedString = String(decoding: decryptedBody, as: UTF8.self)
print(decryptedString)

decryptedString的打印输出类似于这样的";L����JtõJ��E7sD��)�ga�J׊p�">

你知道我做错了什么吗?感谢任何人的帮助。

Key和IV必须进行十六进制解码,CryptoJS代码返回的密文必须进行Base64解码。在解密之前,不必应用任何填充:

let AESKey = [UInt8](hex: "000102030405060708090a0b0c0d0e0f")
let iv = [UInt8](hex: "101112131415161718191a1b1c1d1e1f")
let bufContent = [UInt8](base64: "GErWj4t2vW0u1o1Z9iUNo8gxkO1O0Bl8l3amQ86EKKw=")
let aes = try AES(key: AESKey, blockMode: CBC(iv: iv), padding: .pkcs7)           
let decryptedBody = try aes.decrypt(bufContent)  
let decryptedString = String(bytes: decryptedBody, encoding: .utf8)!
print(decryptedString) // This will be encrypted

请记住,静态IV是不安全的(出于测试目的,这当然可以(。

最新更新