0

我的 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;
}
4

1 回答 1

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];
}
于 2012-11-21T10:03:16.873 回答