美文网首页
IOS RSA分段解密

IOS RSA分段解密

作者: 梦迪达达 | 来源:发表于2022-03-09 10:55 被阅读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; }

    相关文章

      网友评论

          本文标题:IOS RSA分段解密

          本文链接:https://www.haomeiwen.com/subject/enltdrtx.html