Ios 奇怪的加密行为

Ios 奇怪的加密行为,ios,objective-c,cocoa-touch,rsa,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:NSUTF8

我正在尝试使用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);
    }
}
NSData*encryptext(NSString*text,SecKeyRef publicKey)
{
NSCParameterAssert(text.length>0);
NSCParameterAssert(公钥!=NULL);
NSData*dataToEncrypt=[文本数据使用编码:NSUTF8StringEncoding];
const uint8_t*bytesToEncrypt=dataToEncrypt.bytes;
size\u t cipherBufferSize=SecKeyGetBlockSize(公钥);
NSCAssert(cipherBufferSize>11,@“块大小太小:%zd”,cipherBufferSize);
const size\u t inputBlockSize=cipherBufferSize-11;//因为我们将使用PKCS1填充
uint8_t*cipherBuffer=(uint8_t*)malloc(尺寸(uint8_t)*cipherBuffer尺寸);
NSMutableData*累加器=[[NSMutableData alloc]init];
@试一试{
对于(大小块=0;块*inputBlockSize
它在iOS 6上工作正常,但在iOS 5上失败,SecKeyEncrypt返回
-50
errSecParam
)。如果我在
inputBlockSize=cipherBufferSize-11
中将11改为12,它将在iOS5上工作。 Apple doc表示,如果使用PKCS1填充,则输入块长度应小于或等于
SecKeyGetBlockSize()-11
。但在iOS5上,它肯定需要更短的输入

根据文档,我的关键块大小是64,所以输入块的最大长度是53。在iOS 5上,只有52或更少的版本可以工作

这个代码怎么了?或者是iOS 5 Security.framework漏洞

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


相关苹果文档:

请困惑的密码学家注意-RSA密钥的“块大小”指的是模的字节大小:请您添加一个指向您正在阅读的苹果文档的链接。@DuncanJones这里是: