X.509 RSA加密/解密iOS

7

我需要使用X.509 RSA公钥/私钥对来实现加密/解密。

到目前为止,我已经有了一些可以用于加密的东西,但是我没有办法进行解密以进行检查。我尝试的一切都存在读取私钥的问题。

生成密钥对(返回一个.der和一个.pem文件)

openssl req -x509 -out public_key.der -outform der -new -newkey rsa:1024 -keyout private_key.pem -days 3650

加密(不确定是否有效,但看起来是有效的)

+ (NSData *) RSAEncryptData:(NSData *)content {
    SecKeyRef publicKey;
    SecCertificateRef certificate;
    SecPolicyRef policy;
    SecTrustRef trust;
    size_t maxPlainLen;

    NSString *publicKeyPath = [[NSBundle mainBundle] pathForResource:@"public_key" ofType:@"der"];
    NSData *base64KeyData = [NSData dataWithContentsOfFile:publicKeyPath];

    certificate = SecCertificateCreateWithData(kCFAllocatorDefault, ( __bridge CFDataRef) base64KeyData);
    if (certificate == nil) {
        NSLog(@"Can not read certificate from data");
        return nil;
    }

    policy = SecPolicyCreateBasicX509();
    OSStatus returnCode = SecTrustCreateWithCertificates(certificate, policy, &trust);
    if (returnCode != 0) {
        NSLog(@"SecTrustCreateWithCertificates fail. Error Code: %d", (int)returnCode);
        return nil;
    }

    SecTrustResultType trustResultType;
    returnCode = SecTrustEvaluate(trust, &trustResultType);
    if (returnCode != 0) {
        return nil;
    }

    publicKey = SecTrustCopyPublicKey(trust);
    if (publicKey == nil) {
        NSLog(@"SecTrustCopyPublicKey fail");
        return nil;
    }

    maxPlainLen = SecKeyGetBlockSize(publicKey) - 12;


    size_t plainLen = [content length];
    if (plainLen > maxPlainLen) {
        NSLog(@"content(%ld) is too long, must < %ld", plainLen, maxPlainLen);
        return nil;
    }

    void *plain = malloc(plainLen);
    [content getBytes:plain
               length:plainLen];

    size_t cipherLen = 128; // currently RSA key length is set to 128 bytes
    void *cipher = malloc(cipherLen);

    OSStatus encryptReturnCode = SecKeyEncrypt(publicKey, kSecPaddingPKCS1, plain,
                                        plainLen, cipher, &cipherLen);

    NSData *result = nil;
    if (encryptReturnCode != 0) {
        NSLog(@"SecKeyEncrypt fail. Error Code: %d", (int)returnCode);
    }
    else {
        result = [NSData dataWithBytes:cipher
                                length:cipherLen];
    }

    free(plain);
    free(cipher);

    return result;
}

解密

我尝试使用OpenSSL的PEM_read_X509PEM_read_RSAPrivateKey,但都无法读取证书。我甚至还没有通过这一步。如果我能够在不依赖OpenSSL库的情况下完成此操作,那将更好。

+(void)readTest{
    FILE *fp;
    X509 *x;
    NSString *path =[[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"pem"];
    fp=fopen([path UTF8String],"r");

    x=NULL;
    PEM_read_X509(fp,&x,NULL,NULL); // I have also tried PEM_read_RSAPrivateKey

    if (x == NULL) {
        NSLog(@"Cant Read File"); // This ALWAYS fires
    }

    fclose(fp);
    X509_free(x);
}

如果有人能够帮我使用X.509 RSA密钥对进行加密/解密,我会很感激。谢谢。


顺便提一下,证书会在一段时间后过期,您需要继续维护它,当您推送此应用程序时,您将如何进行维护? - thndrkiss
真正的应用程序只使用提供者的公钥加密消息,该公钥通过网络检索。在实际使用中,解密是在服务器端完成的。 - PRNDL Development Studios
我猜想证书无效,因为它们是自签名的。看起来你需要找到一种让它被信任的方法。 - thndrkiss
你是在单元测试中运行此代码吗?如果你是从命令行中运行此代码的,它是否显示你的私钥是有效的?openssl rsa -in private_key.pem -check - quellish
路径传递给fopen是正确的,fp不是NULL或垃圾指针吗? - quellish
显示剩余15条评论
1个回答

9

你卡在哪里了

看起来你的私钥已加密(openssl在命令行上要求输入密码),但是你在尝试打开它时没有解密。此外,private_key.pem是RSA密钥,而不是证书,因此你应该使用PEM_read_RSAPrivateKey。

以下解码代码应该有效:

int pass_cb(char *buf, int size, int rwflag, void* password) {
    snprintf(buf, size, "%s", (char*) password);
    return strlen(buf);
}

+(void)readTest{
    FILE *fp;
    RSA *x;
    NSString *path =[[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"pem"];
    fp=fopen([path UTF8String],"r");

    x = PEM_read_RSAPrivateKey(fp,&x,pass_cb,"key password");

    if (x == NULL) {
        NSLog(@"Cant Read File"); // This ALWAYS fires
    }

    fclose(fp);
    X509_free(x);
}

你也可以生成一个非加密的密钥。在创建密钥和证书时,使用openssl并传递-nodes参数。

请注意,您可能需要确保OpenSSL已正确初始化:

SSL_library_init();
OpenSSL_add_all_algorithms();

此外,OpenSSL还能生成错误消息,这些消息可以帮助您进行开发。您可以使用以下命令加载错误字符串:
SSL_load_error_strings();

您可以这样调用:

ERR_print_errors_fp(stderr);

iOS上的RSA加密和解密

在iOS上,安全框架包含了你需要的一切,因此OpenSSL并不是唯一的解决方案。我猜你使用OpenSSL是因为你不知道如何将私钥文件转换为SecKeyDecrypt所需的有效参数。

诀窍是生成一个PKCS#12文件并调用SecPKCS12Import

你可以使用OpenSSL生成此文件:

openssl x509 -inform der -outform pem -in public_key.der -out public_key.pem
openssl pkcs12 -export -in public_key.pem -inkey private_key.pem -out private_key.p12

这将要求你提供导出密码。此密码应传递给SecPKCS12Import ("key password" 如下所示)。

NSString *privateKeyPath = [[NSBundle mainBundle] pathForResource:@"private_key" ofType:@"p12"];
NSData *pkcs12key = [NSData dataWithContentsOfFile:privateKeyPath];
NSDictionary* options = [NSDictionary dictionaryWithObjectsAndKeys: @"key password", kSecImportExportPassphrase, nil];
CFArrayRef              importedItems = NULL;
OSStatus returnCode = SecPKCS12Import(
                      (__bridge CFDataRef) pkcs12key,
                      (__bridge CFDictionaryRef) options,
                      &importedItems
                      );

importedItems是一个包含所有已导入PKCS12项的数组,基本上就是“身份”(私钥+证书)。

NSDictionary* item = (NSDictionary*) CFArrayGetValueAtIndex(importedItems, 0);
SecIdentityRef  identity = (__bridge SecIdentityRef) [item objectForKey:(__bridge NSString *) kSecImportItemIdentity];
SecKeyRef privateKeyRef;
SecIdentityCopyPrivateKey(identity, &privateKeyRef);

接下来,您可以使用privateKeyRef并使用SecKeyDecrypt进行解密。为了匹配您的加密程序:

size_t cipherLen = [content length];
void *cipher = malloc(cipherLen);
[content getBytes:cipher length:cipherLen];
size_t plainLen = SecKeyGetBlockSize(privateKeyRef) - 12;
void *plain = malloc(plainLen);

OSStatus decryptReturnCode = SecKeyDecrypt(privateKeyRef, kSecPaddingPKCS1, cipher, cipherLen, plain, &plainLen);

这太棒了。我知道我的问题出在哪里了 - 非常感谢。 - PRNDL Development Studios

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接