我正在尝试使用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返回-50
(errSecParam
)。如果我在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