IOS RSA分段解密

2022-03-09  本文已影响0人  梦迪达达

+ (NSData *)decryptData:(NSData *)data privateKey:(NSString *)privKey{ if(!data || !privKey){ return nil; } SecKeyRef keyRef = [RSA addPrivateKey:privKey]; if(!keyRef){ return nil; } return [RSA decryptData:data withKeyRef:keyRef]; }

+ (NSData *)decryptData:(NSData *)cipherData withKeyRef:(SecKeyRef) keyRef{        size_t plainBufferSize = SecKeyGetBlockSize(keyRef);    NSLog(@"plainBufferSize = %zd", plainBufferSize);    uint8_t *plainBuffer = malloc(plainBufferSize * sizeof(uint8_t));    // 计算数据段最大长度及数据段的个数    double totalLength = [cipherData length];    size_t blockSize = plainBufferSize;    size_t blockCount = (size_t)ceil(totalLength / blockSize);    NSMutableData *decryptedData = [NSMutableData data];    // 分段解密    for (int i = 0; i < blockCount; i++) {        NSUInteger loc = i * blockSize;        // 数据段的实际大小。最后一段可能比blockSize小。        int dataSegmentRealSize = MIN(blockSize, totalLength - loc);        // 截取需要解密的数据段        NSData *dataSegment = [cipherData subdataWithRange:NSMakeRange(loc, dataSegmentRealSize)];        OSStatus status = SecKeyDecrypt(keyRef, kSecPaddingPKCS1, (const uint8_t *)[dataSegment bytes], dataSegmentRealSize, plainBuffer, &plainBufferSize);        if (status == errSecSuccess) {            NSData *decryptedDataSegment = [[NSData alloc] initWithBytes:(const void *)plainBuffer length:plainBufferSize];            [decryptedData appendData:decryptedDataSegment];                   } else {            if (plainBuffer) {                free(plainBuffer);            }            return nil;        }    }    if (plainBuffer) {        free(plainBuffer);    }    return decryptedData; }

上一篇下一篇

猜你喜欢

热点阅读