1

I make extension to generate function to encrypt and decrypt with AES like this :

import cryptoswift

extension String {
func aesEncrypt(key: String, iv: String) throws -> String{
    let data = self.dataUsingEncoding(NSUTF8StringEncoding)
    let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data!.arrayOfBytes(), padding: PKCS7())
    let encData = NSData(bytes: enc, length: Int(enc.count))
    let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
    let result = String(base64String)
    return result
}

func aesDecrypt(key: String, iv: String) throws -> String {
    let data = NSData(base64EncodedString: self, options: NSDataBase64DecodingOptions(rawValue: 0))
    let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes(), padding: PKCS7())
    let decData = NSData(bytes: dec, length: Int(dec.count))
    let result = NSString(data: decData, encoding: NSUTF8StringEncoding)
    return String(result!)
}
}

but both aesEncrypt and aesDecrypt have error extra argument 'padding' in call in these line:

let enc = try AES(key: key, iv: iv, blockMode:.CBC).encrypt(data!.arrayOfBytes(), padding: PKCS7())

and

let dec = try AES(key: key, iv: iv, blockMode:.CBC).decrypt(data!.arrayOfBytes(), padding: PKCS7())

How to repair these error?

Update: I am using new way to get aes encryption:

let langinput = "us"
let aes = try AES(key: key, iv: iv) // aes128
let langencrypted = try aes.encrypt(langinput.utf8.map({$0}))
let encData = NSData(bytes: langencrypted, length: Int(langencrypted.count))
let base64String: String = encData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions(rawValue: 0));
let aes_encrypt_result = String(base64String)
jww
  • 97,681
  • 90
  • 411
  • 885
Sarimin
  • 707
  • 1
  • 7
  • 18

1 Answers1

0

AES is a block cipher meaning the data must be a multiple of block size (AES 16-bytes) so padding bytes need to be added during encryption and removed during decryption.

Use RNCryptor, it uses Apple's Common Crypto that is FIPS 140 certified and uses the hardware encryption engine. It provided authenticated AES encryption and if needed password derivation. It is well vetted. Other than that there are several Swift AES implementations on SO.

RNCryptor handles the iv for you prepending it to the encrypted data along with other information. See RNCryptor-Spec. It is not a good choice if you need to interoperate with another implementation.

zaph
  • 111,848
  • 21
  • 189
  • 228