iOS AES错误实现?

时间:2012-11-21 10:03:17

标签: ios cocoa-touch aes

我的AES方法(下面的代码)仅适用于自密码数据。 我不知道哪里出错了。你能建议我一些框架或更好的实施吗?

- (NSData *)aesOperation:(CCOperation)op OnData:(NSData *)data key:(NSString*)inKey {
    NSData *outData = nil;
    int bufferSize = 6000000;
    NSLog(@"AES InData: %@",data);
    if (inKey == NULL) {
        NSLog(@"A klucz to chcesz wyczarować? Podaj klucz do zaszyfrowanego pliku");
        return NULL;
    }

    const void *key = inKey ;
    const void *dataIn = data.bytes;
    size_t dataInLength = data.length;
    // Data out parameters
    size_t outMoved = 0;

    unsigned char outBuffer[bufferSize];
    memset(outBuffer, 0, bufferSize);
    CCCryptorStatus status = -1;

    status = CCCrypt(op, kCCAlgorithmAES128, kCCOptionECBMode, key, kCCKeySizeAES128, NULL,
                     dataIn, dataInLength, &outBuffer, bufferSize, &outMoved);

    if(status == kCCSuccess) {
        outData = [NSData dataWithBytes:outBuffer length:outMoved];
    } else if(status == kCCBufferTooSmall) {

        size_t newsSize = outMoved;
        void *dynOutBuffer = malloc(newsSize);
        memset(dynOutBuffer, 0, newsSize);
        outMoved = 0;

        status = CCCrypt(op,kCCAlgorithmAES128,kCCOptionECBMode,key,kCCKeySizeAES128,NULL,dataIn, dataInLength, &outBuffer, bufferSize, &outMoved);

        if(status == kCCSuccess) {
            outData = [NSData dataWithBytes:outBuffer length:outMoved];
        }
    }
    return outData;
}

1 个答案:

答案 0 :(得分:2)

我找到了使用AES密码/解码的正确方法,它适用于所有人。

- (NSData *)initCipherData:(NSData *)data key:(NSString*)key{
    return [self aesOperation:kCCEncrypt OnData:data key:key];
}

- (NSData *)initDecipherData:(NSData *)data key:(NSString*)key{
    return [self aesOperation:kCCDecrypt OnData:data key:key];
}

- (NSData *)aesOperation:(CCOperation)op 
                  OnData:(NSData *)data 
                     key:(NSString*)inKey {

    const char * key = [inKey UTF8String];
    NSUInteger dataLength = [data length];
    uint8_t unencryptedData[dataLength + kCCKeySizeAES128];
    size_t unencryptedLength;

    CCCrypt(op, 
            kCCAlgorithmAES128, 
            kCCOptionECBMode, 
            key, 
            kCCKeySizeAES128, 
            NULL, 
            [data bytes], 
            dataLength, 
            unencryptedData, 
            dataLength, 
            &unencryptedLength);
    return [NSData dataWithBytes:unencryptedData length:unencryptedLength];
}