Using CommonCrypto with an IV but always returning nil

为君一笑 提交于 2019-11-29 18:16:13

Looks like the iv may be different, ensure that the data bytes are the same and the length is correct.

You want CCCrypt to do one-shot encryption.

From Apple: CCCrypt is a Stateless, one-shot encrypt or decrypt operation. This basically performs a sequence of CCCrytorCreate(), CCCryptorUpdate(), CCCryptorFinal(), and CCCryptorRelease().

Since you are not using CCCrypt then you will have to at least add CCCryptorFinal() to your example.

Also note that the key and iv really need to be exactly the correct size in bytes. Using NSUTF8StringEncoding may not produce the number of bytes expected if there are some characters that require multiple byte encodings. Note: "i" can be encoded as a surrogate pair.

Do not use a password string without using PBKDF2 to generate a good key.

Consider using RNCryptor unless you really know what you are doing with crypto.

Here is simple example code of a one-shot encrypt/decrypy method
The key and iv must be exactly the required length.
Any encoding (Base64, NSString, etc) is done outside of this method.

+ (NSData *)doCipher:(NSData *)dataIn
                  iv:(NSData *)iv
                 key:(NSData *)symmetricKey
             context:(CCOperation)encryptOrDecrypt // kCCEncrypt or kCCDecrypt
               error:(NSError **)error
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( encryptOrDecrypt,
                       kCCAlgorithmAES128,
                       kCCOptionPKCS7Padding,
                       symmetricKey.bytes, 
                       kCCKeySizeAES128,
                       iv.bytes,
                       dataIn.bytes,
                       dataIn.length,
                       dataOut.mutableBytes,
                       dataOut.length,
                       &cryptBytes);

    if (ccStatus == kCCSuccess) {
        dataOut.length = cryptBytes;
    }
    else {
        if (error) {
            *error = [NSError errorWithDomain:@"kEncryptionError"
                                         code:ccStatus
                                     userInfo:nil];
        }
        dataOut = nil;
    }

    return dataOut;
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!