X.509 RSA加密/解密iOS

时间:2014-05-12 18:12:08

标签: ios objective-c encryption rsa x509

我需要使用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_X509 PEM_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对加密/解密,我会很感激。感谢。

1 个答案:

答案 0 :(得分:7)

你被困的地方

您的私钥似乎是加密的(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);
}

或者,您可以生成非加密密钥。在创建密钥和证书时,将-nodes传递给openssl。

请注意,您可能需要确保使用以下命令正确初始化OpenSSL:

SSL_library_init();
OpenSSL_add_all_algorithms();

此外,OpenSSL会生成可帮助您完成开发的错误消息。使用以下命令加载错误字符串:

SSL_load_error_strings();

你可以打电话:

ERR_print_errors_fp(stderr);

iOS上的RSA加密和解密

OpenSSL不是唯一的解决方案,因为iOS上的安全框架包含您需要的一切。我猜你转向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);