RNCryptor: AES128CBC decrypting in Swift

1.6k views Asked by At

How can I decrypt NSData with RNCryptor (AES128CBC)? I already tried to understand the documentation: https://github.com/RNCryptor/RNCryptor-Spec/blob/master/draft-RNCryptor-Spec-v4.0.md

Edit:

class Decription{
    func AES128(message: String, key: String, iv: String){
        let keyData: NSData! = (key as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
        let ivData:  NSData! = (iv as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
        let data:    NSData! = (message as NSString).dataUsingEncoding(NSUTF8StringEncoding) as NSData!
        let cryptData        = NSMutableData(length: Int(data.length) + kCCBlockSizeAES128)!

        let keyLength              = size_t(kCCKeySizeAES256)
        let operation: CCOperation = UInt32(kCCDecrypt)
        let algoritm:  CCAlgorithm = UInt32(kCCAlgorithmAES128)
        let options:   CCOptions   = UInt32(kCCOptionECBMode + kCCOptionPKCS7Padding)

        var numBytesEncrypted :size_t = 0

        let cryptStatus = CCCrypt(
            operation,
            algoritm,
            options,
            keyData.bytes,
            keyLength,
            ivData.bytes,
            data.bytes, data.length,
            cryptData.mutableBytes,
            cryptData.length,
            &numBytesEncrypted
        )

        if UInt32(cryptStatus) == UInt32(kCCSuccess) {
            cryptData.length = Int(numBytesEncrypted)
            print("Decrypted Result = \(NSString(data: cryptData, encoding: NSUTF8StringEncoding))")
        } else {
            print("Error: \(cryptStatus)")
        }
    }
}

I changed the code snippet @zaph linked to. You can see the result above.

NSString(data: cryptData, encoding: NSUTF8StringEncoding) results nil. What is the problem?

1

There are 1 answers

1
zaph On

First you encrypt using RNCryptor, not some other method because RNCryptor is more than just AES encryption, it an entire secure encryption method including key derivation and authentication. See the RNCryptor-Spec for more information.

If you just want decryption use Common Crypto with Swift, see this SO Answer for example code.

Note: The sample code is just that, it should not be used as-is in production code. In particular ECB mode is not secure, use CBC with a random iv and consider adding authentication and key derivation to the password such as PBKDF2.