I'm working on a Swift Framework, connected to my servers. Data are encrypted between the application and the PHP server in AES-256-CBC. I succeed to send data from applications to the server and get the response. But now I'd like to decrypt the response and I can't.
To decrypt the server response I use a vector (sent by the server in Base64), the source data and a key (generated application-side). When I do a base64Decode on my vector, base64 returns nil. It returns nil because my vector contains some special characters and Strings don't handle special char. The problem is, I need a string and my vector to do an AES Decrypt and get back my data.
This is my Swift 3 code :
let data = Data(base64Encoded: data)!
let decrypted = try! AES(key: key, iv: iv.base64Decoded()!, blockMode: .CBC, padding: PKCS7()).decrypt([UInt8](data))
let decryptedData = Data(decrypted)
And on the second line I get the following error:
Fatal error: unexpectedly found nil while unwrapping an Optional value
EDIT :
Precisely, this is what happened :
First I created, server-side, a random vector in PHP :
openssl_random_pseudo_bytes(openssl_cipher_iv_length("AES-256-CBC"));
... and encode it in base64 because it's composed with special characters.
Now, application-side I try to decode it :
extension String {
func base64Decoded() -> String? {
if let data = Data(base64Encoded: self) {
return String(data: data, encoding: .utf8)
}
return nil
}
}
let myVector = iv.base64Decoded()!
But that fail, because the decoded string contain non handled characters. How can I handle them ?
Thanks for all your ideas