Suat Alkan
Suat Alkan

Reputation: 39

CryptoSwift throws invalidKeySize because of base64 encoded aesKey and aesIV

I have a project that retrieve data from API and shows in the app. But API uses AES encryption, I have aesKey and aesIV key and these keys are base64 encoded. I need to encode another string with these keys. To do that I use CryptoSwift library but when I try to use this keys to cipher the string, swift console warns me about invalidKeySize.I tried to decode from base64 to string but it did not work as well. These are the keys for an example;

Key and IV size are AES256, for encryption and decryption I need to use PKCS7 padding type with ECB/CBC block mode

aesKey = lHLBfVxlGoKoaCqWORJEHh3jOvC2EBx2VHGyNAdqYV0=
aesIV = 2spaSfljZ/cunRbuVkdphQ==

and CryptoSwift code block is:

let aes = try AES(key: "\(aesKeyString)", iv: "\(aesIVString)")
let cipherText = try aes.encrypt(Array("all".utf8))

Upvotes: 2

Views: 1966

Answers (1)

Marcin
Marcin

Reputation: 3784

The aesKey and aesIV from the snippet is Base64 encoded, so it's not really useful in that form. The convenience initializer you used is for a String, not base64 encoded data that you provided (that happened to be string, but it's different).

let aesKey = "lHLBfVxlGoKoaCqWORJEHh3jOvC2EBx2VHGyNAdqYV0="
let key = [UInt8](base64: aesKey)

let aesIV = "2spaSfljZ/cunRbuVkdphQ=="
let iv = [UInt8](base64: aesIV)

let aes = try AES(key: key, blockMode: CBC(iv: iv))
let cipherText = try aes.encrypt(Array("all".utf8))

Upvotes: 5

Related Questions