2

String for encryption "secret"

after encryption "64c2VjcmV0"

this is the code that works properly

    let inputNSData: NSData = input.dataUsingEncoding(NSUTF8StringEncoding)!
    let inputBytes: [UInt8] = inputNSData.arrayOfBytes()
    let key: [UInt8] = self.generateArray("secret0key000000") //16
    let iv: [UInt8] = self.generateArray("0000000000000000")  //16
    do {
        let encrypted: [UInt8] = try AES(key: key, iv: iv, blockMode: .CBC).encrypt(inputBytes, padding: PKCS7())    
        let decrypted: [UInt8] = try AES(key: key, iv: iv, blockMode: .CBC).decrypt(encrypted, padding: PKCS7())   
        let decryptNsData: NSData = NSData(bytes: decrypted, length: decrypted.count)     
        let c = decryptNsData.base64EncodedStringWithOptions(NSDataBase64EncodingOptions.Encoding64CharacterLineLength)
        let decryptedString: String = NSString(data: decryptNsData, encoding: NSUTF8StringEncoding) as! String
        print("String after decryption\t\(decryptedString)")
    } catch {
        // some error
    }

but i could not decrypt by using the same key and iv I am getting fatal error: unexpectedly found nil while unwrapping an Optional value for the encrypted string

    let key: [UInt8] = self.generateArray("secret0key000000") //16
    let iv: [UInt8] = self.generateArray("0000000000000000")  //16
    let input: String = "64c2VjcmV0"

    var encryptedStrData = NSData(base64EncodedString: input, options: NSDataBase64DecodingOptions())!
    let inputBytes: [UInt8] = encryptedStrData.arrayOfBytes()
    print("String in uint8\(inputBytes)")
    //var keyData = keyStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    //var ivData:NSData = ivStr.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)!
    do{
    let decryptedTryData = try AES(key: key, iv: iv, blockMode: .CBC).decrypt(inputBytes)
        print(decryptedTryData)
    }
    catch{

    }

I am getting fatal error: unexpectedly found nil while unwrapping an Optional value for the encrypted string

jww
  • 97,681
  • 90
  • 411
  • 885
Cloy
  • 2,141
  • 23
  • 32
  • The length of a Base64 string should be divisible by 4. Your input 64bXVkaXRjbmU= is 14 char long .. and is thuse not a valid base64 string – Ebbe M. Pedersen Oct 26 '15 at 10:16
  • Thank you @Ebbe M. Pedersen for the concern.....i gor what you are suggesting but could you tell me what is wrong in the code that has resulted in improper base64 strings – Cloy Oct 26 '15 at 12:03

3 Answers3

4

You are using Base64 when it is not necessary, only Base64 encode non string data.

Here is the first test code:

let inputBytes: [UInt8] = Array("secret".utf8)
let key:        [UInt8] = Array("secret0key000000".utf8) //16
let iv:         [UInt8] = Array("0000000000000000".utf8)  //16

var encryptedBase64 = ""
do {
    let encrypted: [UInt8] = try AES(key: key, iv: iv, blockMode: .CBC).encrypt(inputBytes, padding: PKCS7())
    let encryptedNSData = NSData(bytes: encrypted, length: encrypted.count)
    encryptedBase64 = encryptedNSData.base64EncodedStringWithOptions([])

    let decrypted: [UInt8] = try AES(key: key, iv: iv, blockMode: .CBC).decrypt(encrypted, padding: PKCS7())
    let result = String(bytes: decrypted, encoding: NSUTF8StringEncoding)!
    print("result\t\(result )")
} catch {
    // some error
}
print("encryptedBase64: \(encryptedBase64)")

Output:

result: secret
encryptedBase64: 0OCxa0yJszq9MvkrWjn3wg==

let encryptedData = NSData(base64EncodedString: encryptedBase64, options:[])!
print("decodedData: \(encryptedData)")
let encrypted = Array(UnsafeBufferPointer(start: UnsafePointer<UInt8>(encryptedData.bytes), count: encryptedData.length))

do {
    let decryptedData = try AES(key: key, iv: iv, blockMode: .CBC).decrypt(encrypted)
    let decryptedString = String(bytes: decryptedData, encoding: NSUTF8StringEncoding)!
    print("decryptedString: \(decryptedString)")

}
catch{
    // some error
}

Output:

decryptedString: secret

Notes:

Don't use CryptoSwift, it does not use the build-in encryption hardware and is 400 to 1000 times slower than the Apple Security.framework Common Crypto. It is also not well vetted and used non-certified encryption code.

Don't use a string directly as the key, it is not secure. Instead derive a key from the string using PBKDK2 (Password Based Key Derivation Function).

zaph
  • 111,848
  • 21
  • 189
  • 228
0

Base64 strings must be divisible by 4. Yours is not. You can use a website, such as https://www.base64decode.org, to test your strings.

Морт
  • 1,163
  • 9
  • 18
  • Thank you @Морт for the concern.....i gor what you are suggesting but could you tell me what is wrong in the code that has resulted in improper base64 strings – Cloy Oct 26 '15 at 12:03
0

For Swift3 (to avoid the UnsafePointer error) this has worked for me for the second part (decoding the base64 variable):

let encryptedData = NSData(base64Encoded: encryptedBase64, options:[])!
print("decodedData: \(encryptedData)")

let count = encryptedData.length / MemoryLayout<UInt8>.size

// create an array of Uint8
var encrypted = [UInt8](repeating: 0, count: count)
// copy bytes into array
encryptedData.getBytes(&encrypted, length:count * MemoryLayout<UInt8>.size)

do {
    let decryptedData = try AES(key: key, iv: iv, blockMode: .CBC).decrypt(encrypted)
    let decryptedString = String(bytes: decryptedData, encoding: String.Encoding.utf8)!
    print("decryptedString: \(decryptedString)")

}
catch{
    // some error
}
Kostas
  • 367
  • 1
  • 3
  • 17