奇怪的SecKeyEncrypt行为

时间:2013-01-23 14:24:11

标签: ios objective-c cocoa-touch rsa

我正在尝试使用SecKeyEncrypt函数通过PKCS1填充实现RSA加密。

代码如下:

NSData *encryptText(NSString *text, SecKeyRef publicKey)
{
    NSCParameterAssert(text.length > 0);
    NSCParameterAssert(publicKey != NULL);
    NSData *dataToEncrypt = [text dataUsingEncoding:NSUTF8StringEncoding];
    const uint8_t *bytesToEncrypt = dataToEncrypt.bytes;

    size_t cipherBufferSize = SecKeyGetBlockSize(publicKey);
    NSCAssert(cipherBufferSize > 11, @"block size is too small: %zd", cipherBufferSize);

    const size_t inputBlockSize = cipherBufferSize - 11; // since we'll use PKCS1 padding
    uint8_t *cipherBuffer = (uint8_t *) malloc(sizeof(uint8_t) * cipherBufferSize);

    NSMutableData *accumulator = [[NSMutableData alloc] init];

    @try {

        for (size_t block = 0; block * inputBlockSize < dataToEncrypt.length; block++) {
            size_t blockOffset = block * inputBlockSize;
            const uint8_t *chunkToEncrypt = (bytesToEncrypt + block * inputBlockSize);
            const size_t remainingSize = dataToEncrypt.length - blockOffset;
            const size_t subsize = remainingSize < inputBlockSize ? remainingSize : inputBlockSize;

            size_t actualOutputSize = cipherBufferSize;
            OSStatus status = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, chunkToEncrypt, subsize, cipherBuffer, &actualOutputSize);

            if (status != noErr) {
                NSLog(@"Cannot encrypt data, last SecKeyEncrypt status: %ld", status);
                return nil;
            }

            [accumulator appendBytes:cipherBuffer length:actualOutputSize];
        }

        return [accumulator copy];
    }
    @finally {
        free(cipherBuffer);
    }
}

它在iOS 6上完美运行,但在iOS 5上失败,SecKeyEncrypt返回-50errSecParam)。如果我在inputBlockSize = cipherBufferSize - 11中将11更改为12,它将适用于iOS 5。 Apple doc说如果使用PKCS1填充,输入块长度应该小于或等于SecKeyGetBlockSize() - 11。但是在iOS 5上它肯定需要更短的输入。

根据文档,我的密钥块大小为64,因此输入块最大长度为53。在iOS 5上只有52或更少可用。

这段代码有什么问题?或者它是iOS 5 Security.framework错误?

UPD:问题仅使用512位密钥重现。尝试使用生成的1024位密钥,代码在iOS 5上使用11

相关Apple文档:http://developer.apple.com/library/ios/documentation/Security/Reference/certifkeytrustservices/Reference/reference.html#//apple_ref/c/func/SecKeyEncrypt

0 个答案:

没有答案