0

i have used CryptoSwift for AES encryption/decryption. when i run this code it throws error:

"fatal error: Array index out of range".

using reference from here

What can be the cause for this? Any suggestion will be most appreciate.

code:

 let key = "1234567890123456" // key
   let iv = "1234567890123456" // random
   let message = "This is test string"

    override func viewDidLoad() {
        super.viewDidLoad()

    // encrypt
    let encrypted = AES(key: key, iv: iv, blockMode: .CBC)
    let enc =  encrypted?.encrypt(message.utf8Array, padding: PKCS7())
    println("enc >>  \(enc)")

    // decrypt
    let decrypted = AES(key: key, iv: iv, blockMode: .CBC)
    let dec =  encrypted?.decrypt(enc!, padding: PKCS7())
    println("dec >>  \(dec)")
jww
  • 97,681
  • 90
  • 411
  • 885
Ruchi
  • 5,032
  • 13
  • 59
  • 84
  • 1
    Do not use CryptoSwift, all the primitives are home-grown implementations and may have errors/weaknesses/backdoors. Use a library that uses Apple's Common Crypto which is well vetted. Additionally CryptoSwift lacks key cryptographic primitives such as PBKDF2 for deriving keys from passwords which is used to help make passwords into secure keys. Also missing is obtaining random data for use as an iv among other critical usages. Apple's iOS CoreCrypto Kernel Module is [FIPS-140-2 certified](http://csrc.nist.gov/groups/STM/cmvp/documents/140-1/140sp/140sp1514.pdf). – zaph Jun 15 '15 at 14:55
  • Hi, I am not getting any relevant solution yet for Common Crypto. can you please help me on this. if you have idea about this. i need AES crypto using swift. – Ruchi Jun 16 '15 at 07:19
  • Take a look at this [SO Answer](http://stackoverflow.com/a/29230965/451475) – zaph Jun 16 '15 at 10:22
  • 1
    Note: CryptoSwift is over 1000 times slower than Apple's Common Crypto CCCrypt on an iPhone 6. – zaph Aug 10 '15 at 23:23

1 Answers1

0

The problem may be here: message.utf8Array, where you convert String to Array. Here is working example:

    let key = "1234567890123456" // key
    let iv = "1234567890123456" // random
    let message = "This is test string"

    let aes = AES(key: key, iv: iv, blockMode: .CBC)

    // encrypt
    let enc = try! aes?.encrypt(message.dataUsingEncoding(NSUTF8StringEncoding)!.arrayOfBytes(), padding: PKCS7())
    print("enc >>  \(enc)")

    // decrypt
    let dec =  try! aes?.decrypt(enc!, padding: PKCS7())
    let str = NSString(data: NSData.withBytes(dec!), encoding: NSUTF8StringEncoding)
    print("dec >>  \(str)")
Marcin
  • 3,694
  • 5
  • 32
  • 52