目标c RSA与OAEP填充sha256之前的ios 10

时间:2018-04-18 19:06:04

标签: ios encryption rsa sha256

我正在使用RSA加密方法在iPhone中使用加密方法,到目前为止,我可以使用此方法获取加密字符串,该字符串已被服务器成功解密。

SecKeyRef keyRef = [self addPublicKey:pubKey];

SecKeyAlgorithm algorithm = kSecKeyAlgorithmRSAEncryptionOAEPSHA256;

if (!keyRef) {
    return nil;
}

BOOL canEncrypt =  SecKeyIsAlgorithmSupported(keyRef, kSecKeyOperationTypeEncrypt, algorithm);

if (canEncrypt) {
    CFErrorRef error = NULL;
    NSData *encryptedData = (NSData *)CFBridgingRelease(
                                                        SecKeyCreateEncryptedData(keyRef, algorithm, (__bridge CFDataRef) content, &error)
    );

    if (encryptedData) {
        return encryptedData;
    }else{
        NSError *err = CFBridgingRelease(error);
        NSLog(@"Ocurrió un error %@", err.localizedDescription);
        return nil;
    }
}

此方法适用于ios 10及更新版本,我需要知道如何在以前的ios版本中设置算法,我的代码如下

SecKeyRef keyRef = [self addPublicKey:pubKey];
if (!keyRef) {
    return nil;
}

size_t cipherBufferSize = SecKeyGetBlockSize(keyRef);
uint8_t *cipherBuffer = malloc(cipherBufferSize * sizeof(uint8_t));
memset((void *)cipherBuffer, 0*0, cipherBufferSize);

NSData *plainTextBytes = content;
size_t blockSize = cipherBufferSize - 11;
size_t blockCount = (size_t)ceil([plainTextBytes length] / (double)blockSize);

NSMutableData *encryptedData = [NSMutableData dataWithCapacity:0];

for (int i=0; i<blockCount; i++) {

    int bufferSize = (int)MIN(blockSize,[plainTextBytes length] - i * blockSize);
    NSData *buffer = [plainTextBytes subdataWithRange:NSMakeRange(i * blockSize, bufferSize)];
    OSStatus status = SecKeyEncrypt(keyRef,
                                    kSecPaddingOAEP,
                                    (const uint8_t *)[buffer bytes],
                                    [buffer length],
                                    cipherBuffer,
                                    &cipherBufferSize);

    if (status == noErr){
        NSData *encryptedBytes = [NSData dataWithBytes:(const void *)cipherBuffer length:cipherBufferSize];
        [encryptedData appendData:encryptedBytes];

    }else{

        if (cipherBuffer) {
            free(cipherBuffer);
        }
        return nil;
    }
}
if (cipherBuffer) free(cipherBuffer);

到目前为止,我可以看到在ios 10的版本中,您可以使用此行设置算法

SecKeyAlgorithm algorithm = kSecKeyAlgorithmRSAEncryptionOAEPSHA256;

我的问题是,如何在早期版本的ios中获得该算法,我发布的第二个代码无法解密。

感谢您的帮助

1 个答案:

答案 0 :(得分:0)

如果对MyShimmedClass使用OAEP填充,则只能使用SecKeyEncrypt,即SHA1。不幸的是,您不能将OAEP SHA256与kSecPaddingOAEP一起使用。