使用Keychain存储密钥在iOS中生成OpenSSL证书签名请求 [英] Generating an OpenSSL Certificate Signing Request in iOS with Keychain stored keys
问题描述
我正在尝试在iOS中生成CSR。由于显然iOS的Apple安全框架不包括CSR生成方法,我必须为我的项目编译OpenSSL源代码。
I'm trying to generate a CSR in iOS. Since apparently the Apple security framework for iOS doesn't include methods for CSR generation I had to compile the OpenSSL source code for my project.
现在我想知道如何将这些方法与我之前在Keychain中生成的密钥一起使用。也就是说,我需要将SecKeyRef类型转换为OpenSSL类型,如EVP_PKEY。那将允许我调用OpenSSL方法X509_REQ_set_pubkey。
Now I want to know how to use these methods with the keys I've generated in the Keychain previously. That is, I need to convert SecKeyRef type into OpenSSL types like EVP_PKEY. That will allow me to call the OpenSSL method X509_REQ_set_pubkey.
有没有人知道实现这个目标的方法?
Does anyone know a way to achieve this?
推荐答案
自己找到解决方案。
首先,您需要从钥匙串中提取密钥作为NSData。
First of all you need to extract the key from the Keychain as NSData.
- (NSData *) getKeyDataWithIdentifier:(NSString *) identifier
{
NSData * keyBits = nil;
NSMutableDictionary * keyQuery = [[NSMutableDictionary alloc] init];
NSData * encodedId = [identifier dataUsingEncoding:NSUTF8StringEncoding];
[keyQuery setObject:encodedId forKey:kSecAttrApplicationTag];
[keyQuery setObject:kSecClassKey forKey:kSecClass];
[keyQuery setObject:[NSNumber numberWithBool:YES] forKey:kSecReturnData];
[keyQuery setObject:kSecAttrKeyTypeRSA forKey:kSecAttrKeyType];
OSStatus sanityCheck = SecItemCopyMatching((CFDictionaryRef)keyQuery, (CFTypeRef *)&keyBits);
if (sanityCheck != noErr) {
NSLog(@"Error: %ld", sanityCheck);
}
return keyBits;
}
现在我们需要将此数据转换为unsigned char并将其提供给方法d2i_RSAPublicKey
Now we need to cast this data as unsigned char and give it to the method d2i_RSAPublicKey
- (void) generateCSR:(NSData *) keyData
{
X509_REQ *req = NULL;
X509_NAME *name= NULL;
EVP_PKEY *key;
const unsigned char * bits = (unsigned char *) [keyData bytes];
int length = [keyData length];
if ((req=X509_REQ_new()) == NULL) {
NSLog(@"big error");
return;
}
RSA * rsa = NULL;
key=EVP_PKEY_new();
d2i_RSAPublicKey(&rsa, &bits, length);
EVP_PKEY_assign_RSA(key,rsa);
name = X509_REQ_get_subject_name(req);
X509_REQ_set_pubkey(req, key);
/* This function creates and adds the entry, working out the
* correct string type and performing checks on its length.
* Normally we'd check the return value for errors...
*/
X509_NAME_add_entry_by_txt(name,"CN",
MBSTRING_ASC, "My certificate request", -1, -1, 0);
X509_REQ_print_fp(stdout, req);
}
使用公钥生成OpenSSL(未签名)中的简单CSR一个通用名称并将其打印到标准输出。
That generates a simple CSR in OpenSSL (not signed) with a public key and a common name and prints it to the standard out.
这篇关于使用Keychain存储密钥在iOS中生成OpenSSL证书签名请求的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!