Objective c RSA 带有 OAEP 填充 sha256 之前的 ios 10

dan*_*511 5 encryption rsa sha256 ios

我正在使用 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;
    }
}
Run Code Online (Sandbox Code Playgroud)

此方法适用于 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);
Run Code Online (Sandbox Code Playgroud)

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

SecKeyAlgorithm algorithm = kSecKeyAlgorithmRSAEncryptionOAEPSHA256;
Run Code Online (Sandbox Code Playgroud)

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

谢谢你的帮助

ksp*_*rin 1

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