0

My AES method (code below) works only with it self cipher data. I don't know where it goes wrong. Could you suggest me someframework or better implementation?

- (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;
}
BW4
  • 111
  • 10

1 Answers1

2

I found proper way to use AES cipher/decipher which works well with everybody.

- (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];
}
Alex Cio
  • 6,014
  • 5
  • 44
  • 74
BW4
  • 111
  • 10
  • Great solution! I had a problem with the key length and could fix it. If your looking for en and decoding for `iOS` and `Android` have a look at this post, maybe it is helpful for you http://stackoverflow.com/a/19219611/1141395 – Alex Cio Nov 27 '13 at 14:52