The below swift code works to decrypt encrypted values from my encrypters on Dart, Android and Javascript.
The problem is that that the key derivation takes way too long (~15-20 seconds). This uses CryptoSwift. I realize that a release build would reduce it a lot, but not enough.
Is there a better way to generate the PBKDF2 key? PBKDF2 key derivation is suitably fast on my other platforms @ 10,000+ iterations.
import CryptoSwift
func decryptGCM (cipherTextEnc:String, masterPass:String) -> String {
do {
let cipherEncComps = cipherTextEnc.components(separatedBy: "-")
// GET ENCRYPTED VALS
let ivString = cipherEncComps[0]
print (ivString)
let saltString = cipherEncComps[1]
print (saltString)
let cipherTextString = cipherEncComps[2]
print (cipherTextString)
// CREATE SALT (Decode Base64 to UTF8)
let salt = [UInt8](base64: saltString)
// CREATE IV (Decode Base64 to UTF8)
let iv = [UInt8](base64: ivString)
// CREATE decodedCipherString (Decode Base64 to UTF8)
let cipherData = [UInt8](base64: cipherTextString)
// CREATE KEY & DECRYPT
let password: [UInt8] = Array(masterPass.utf8)
/* Generate a key from a `password`. Optional if you already have a key */
let key = try PKCS5.PBKDF2(
password: password,
salt: salt,
iterations: 10000,
keyLength: 32, /* AES-256 */
variant: .sha256
).calculate()
print ("key generated")
let gcm = GCM(iv: iv, mode: .combined)
let aes = try AES(key: key, blockMode: gcm, padding: .noPadding)
let cipherTextBytes = try aes.decrypt(cipherData)
let cipherText = String(decoding: cipherTextBytes, as: UTF8.self)
print ("cipherTextGenerated")
return cipherText
} catch {
print("CAUGHT!")
let errorString = "error in key derivation"
return errorString
}
}