如何从NSData中分割字节?

时间:2017-04-07 04:48:42

标签: ios objective-c iphone byte nsdata

所以..我从服务器加密了需要解密的数据,以便我可以获得完整的响应JSON。问题是我需要分割前16个字节的数据以获得用于解密的IV,其余的字节是加密数据。我试过以下方法:

NSData *wholeData = [[NSData alloc] initWithBase64EncodedString:@"IYSaYh92saFT5t/ueQQtlTaFT1oW33FXPLDUsRMATBLUrY/6Z1VGK1KFmyeRwHpbi85T7ZNzDQAl5v8cu60DcJLwVQDI6KdwbmCq0+L62IM7Ixw60+G8gTkm+6+MLtyE" options:0];

NSData *d1 = [wholeData subdataWithRange:NSMakeRange(0, 16)];
NSData *d2 = [wholeData subdataWithRange:NSMakeRange(17, wholeData.length)];

NSData *enc = d2;
NSData *key = [[NSData alloc] initWithBase64EncodedString:@"alskd81039aisdf/tusd8341iasldkjfY=" options:0];
NSData *enciv = d1;

NSData *decrypted = [FBEncryptorAES decryptData:enc key:key iv:enciv];

然后我得到了以下错误:

  

由于未捕获的异常'NSRangeException'而终止应用程序,原因:'*** - [NSConcreteData subdataWithRange:]:范围{16,96}超出数据长度96'

如何解决我的问题?

2 个答案:

答案 0 :(得分:1)

NSData *d2 = [wholeData subdataWithRange:NSMakeRange(17, wholeData.length - 17)];

答案 1 :(得分:0)

你可以试试这个

 NSData* blob;
    NSUInteger length = [blob length];
    NSUInteger chunkSize = 100 * 1024;
    NSUInteger offset = 0;
    do {
        NSUInteger thisChunkSize = length - offset > chunkSize ? chunkSize : length - offset;
        NSData* chunk = [NSData dataWithBytesNoCopy:(char *)[blob bytes] + offset
                                             length:thisChunkSize
                                       freeWhenDone:NO];
        offset += thisChunkSize;
        // do something with chunk
    } while (offset < length);