如何将NSData作为密钥和IV发送给CCCrypt

时间:2016-03-25 23:14:16

标签: ios objective-c encryption aes

我需要AES128使用密钥加密16字节数据块,使用IV加密16字节AES模块。

我见过的每个CCCrypt示例都包含了(NSString *)key和IV。我的密钥和IV是NSData 16字节。我已将NSData转换为十六进制字符串,但结果不正确。当我这样做时,我得到一个32字节的AES块。

所以我的问题是,我需要做些什么才能将NSData作为const void *读入CCCrypt?

- (NSData *)AES128Operation:(CCOperation)operation key:(NSString *)key iv:(NSString *)iv theData:(NSData *)theData
{
    char keyPtr[kCCKeySizeAES128 + 1];
    bzero(keyPtr, sizeof(keyPtr));
    [key getCString:keyPtr maxLength:sizeof(keyPtr) encoding:NSUTF8StringEncoding];

    char ivPtr[kCCBlockSizeAES128 + 1];
    bzero(ivPtr, sizeof(ivPtr));
    if (iv) {
        [iv getCString:ivPtr maxLength:sizeof(ivPtr) encoding:NSUTF8StringEncoding];
    }

    NSUInteger dataLength = [theData length];
    size_t bufferSize = dataLength + kCCBlockSizeAES128;
    void *buffer = malloc(bufferSize);

    size_t numBytesEncrypted = 0;
    CCCryptorStatus cryptStatus = CCCrypt(operation,
                                          kCCAlgorithmAES128,
                                          kCCOptionECBMode,
                                          keyPtr,
                                          kCCBlockSizeAES128,
                                          ivPtr,
                                          [theData bytes],
                                          dataLength,
                                          buffer,
                                          bufferSize,
                                          &numBytesEncrypted);


    if (cryptStatus == kCCSuccess) {
        return [NSData dataWithBytesNoCopy:buffer length:numBytesEncrypted];
    }
    free(buffer);
    return nil;
}

1 个答案:

答案 0 :(得分:1)

+ (NSData *)AES128:(NSData *)dataIn
         operation:(CCOperation)operation  // kCC Encrypt, Decrypt
               key:(NSData *)key
           options:(CCOptions)options      // kCCOption PKCS7Padding, ECBMode,
                iv:(NSData *)iv
             error:(NSError **)error
{
    CCCryptorStatus ccStatus   = kCCSuccess;
    size_t          cryptBytes = 0;
    NSMutableData  *dataOut    = [NSMutableData dataWithLength:dataIn.length + kCCBlockSizeAES128];

    ccStatus = CCCrypt( operation,
                       kCCAlgorithmAES,
                       options,
                       key.bytes, key.length,
                       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;
}