如何从 DER/PEM 文件中获取 SecKeyRef



我需要将我的iPhone应用程序与系统集成,它们需要通过给定的公钥加密数据,有3个不同格式的3个文件.xml.der和.pem,我已经研究并找到了一些关于从DER/PEM获取SecKeyRef的文章,但它们总是返回nil。下面是我的代码:

NSString *pkFilePath = [[NSBundle mainBundle] pathForResource:@"PKFile" ofType:@"der"];
NSData *pkData = [NSData dataWithContentsOfFile:pkFilePath]; 
SecCertificateRef   cert; 
cert = SecCertificateCreateWithData(NULL, (CFDataRef) pkData);
assert(cert != NULL);
OSStatus err;
    if (cert != NULL) {
        err = SecItemAdd(
                         (CFDictionaryRef) [NSDictionary dictionaryWithObjectsAndKeys:
                                            (id) kSecClassCertificate,  kSecClass, 
                                            (id) cert,                  kSecValueRef,
                                            nil
                                            ], 
                         NULL
                         );
        if ( (err == errSecSuccess) || (err == errSecDuplicateItem) ) {
            CFArrayRef certs = CFArrayCreate(kCFAllocatorDefault, (const void **) &cert, 1, NULL); 
            SecPolicyRef policy = SecPolicyCreateBasicX509();
            SecTrustRef trust;
            SecTrustCreateWithCertificates(certs, policy, &trust);
            SecTrustResultType trustResult;
            SecTrustEvaluate(trust, &trustResult);
            if (certs) {
                CFRelease(certs);
            }
            if (trust) {
                CFRelease(trust);
            }
            return SecTrustCopyPublicKey(trust);
        }
    }
return NULL;

问题发生在 SecCertificateCreateWithData,它总是返回 nil 即使通过读取文件也可以。有人这样做了,请帮助我,谢谢!

编辑:证书文件是MD5签名。

我在同样的问题上挣扎了很多,终于找到了解决方案。我的问题是我需要同时使用外部私钥和公钥来加密/解密 iOS 应用程序中的数据,并且不想使用钥匙串。事实证明,您还需要iOS安全库的签名证书才能读取密钥数据,当然文件必须采用正确的格式。程序基本如下:

假设您有一个 PEM 格式的私钥(带有 -----BEGIN RSA PRIVATE KEY----- 和 -----END RSA PRIVATE KEY----- 标记(:rsaPrivate.pem

//Create a certificate signing request with the private key
openssl req -new -key rsaPrivate.pem -out rsaCertReq.csr
//Create a self-signed certificate with the private key and signing request
openssl x509 -req -days 3650 -in rsaCertReq.csr -signkey rsaPrivate.pem -out rsaCert.crt
//Convert the certificate to DER format: the certificate contains the public key
openssl x509 -outform der -in rsaCert.crt -out rsaCert.der
//Export the private key and certificate to p12 file
openssl pkcs12 -export -out rsaPrivate.p12 -inkey rsaPrivate.pem -in rsaCert.crt

现在您有两个与iOS安全框架兼容的文件:rsaCert.der(公钥(和rsaPrivate.p12(私钥(。假设文件已添加到捆绑包中,下面的代码在公钥中读取:

- (SecKeyRef)getPublicKeyRef {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaCert" ofType:@"der"];
    NSData *certData = [NSData dataWithContentsOfFile:resourcePath];
    SecCertificateRef cert = SecCertificateCreateWithData(NULL, (CFDataRef)certData);
    SecKeyRef key = NULL;
    SecTrustRef trust = NULL;
    SecPolicyRef policy = NULL;
    if (cert != NULL) {
        policy = SecPolicyCreateBasicX509();
        if (policy) {
            if (SecTrustCreateWithCertificates((CFTypeRef)cert, policy, &trust) == noErr) {
                SecTrustResultType result;
                OSStatus res = SecTrustEvaluate(trust, &result);
                //Check the result of the trust evaluation rather than the result of the API invocation.
                if (result == kSecTrustResultProceed || result == kSecTrustResultUnspecified) {
                    key = SecTrustCopyPublicKey(trust);
                }
            }
        }
    }
    if (policy) CFRelease(policy);
    if (trust) CFRelease(trust);
    if (cert) CFRelease(cert);
    return key;
}

要读取私钥,请使用以下代码:

SecKeyRef getPrivateKeyRef() {
    NSString *resourcePath = [[NSBundle mainBundle] pathForResource:@"rsaPrivate" ofType:@"p12"];
    NSData *p12Data = [NSData dataWithContentsOfFile:resourcePath];
    NSMutableDictionary * options = [[NSMutableDictionary alloc] init];
    SecKeyRef privateKeyRef = NULL;
    //change to the actual password you used here
    [options setObject:@"password_for_the_key" forKey:(id)kSecImportExportPassphrase];
    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    OSStatus securityError = SecPKCS12Import((CFDataRef) p12Data,
                                             (CFDictionaryRef)options, &items);
    if (securityError == noErr && CFArrayGetCount(items) > 0) {
        CFDictionaryRef identityDict = CFArrayGetValueAtIndex(items, 0);
        SecIdentityRef identityApp =
        (SecIdentityRef)CFDictionaryGetValue(identityDict,
                                             kSecImportItemIdentity);
        securityError = SecIdentityCopyPrivateKey(identityApp, &privateKeyRef);
        if (securityError != noErr) {
            privateKeyRef = NULL;
        }
    }
    [options release];
    CFRelease(items);
    return privateKeyRef;
}

从 iOS 10 开始,实际上可以导入 PEM 私钥,而无需将它们转换为 PKCS#12(这是一种非常通用的容器格式,适用于与密码学相关的所有内容(,因此也可以在命令行上使用 OpenSSL 或静态链接应用程序。在macOS上,甚至可以从10.7开始使用与此处提到的功能不同的功能(但到目前为止,iOS尚不存在(。不过,下面描述的方式也适用于macOS 10.12及更高版本。

要导入证书,只需剥离

-----BEGIN CERTIFICATE-----

-----END CERTIFICATE-----

行,然后运行base64解码对剩下的数据,结果是标准DER格式的证书,只需馈送到SecCertificateCreateWithData()即可得到SecCertificateRef。这一直有效,在iOS 10之前也是如此。

要导入私钥,可能需要一些额外的工作。如果私钥包装有

-----BEGIN RSA PRIVATE KEY-----

那么这很容易。同样,需要剥离第一行和最后一行,其余数据需要进行base64解码,结果是PKCS#1格式的RSA密钥。这种格式只能容纳RSA密钥,并且可以直接读取,只需将解码的数据馈入SecKeyCreateWithData()即可获得SecKeyRefattributes字典只需要以下键/值对:

  • kSecAttrKeyTypekSecAttrKeyTypeRSA
  • kSecAttrKeyClasskSecAttrKeyClassPrivate
  • kSecAttrKeySizeInBitsCFNumberRef密钥中的位数(例如 1024、2048 等(如果不知道,这些信息实际上可以从原始密钥数据中读取,即 ASN.1 数据(这有点超出本答案的范围,但我将在下面提供一些有关如何解析该格式的有用链接(。此值可能是可选的!在我的测试中,实际上没有必要设置此值;如果不存在,API 会自行确定该值,并且以后始终正确设置该值。

如果私钥被 -----BEGIN PRIVATE KEY----- 包装,则 base64 编码数据不是 PKCS#1 格式,而是 PKCS#8 格式,但是,这只是一个更通用的容器,也可以容纳非 RSA 密钥,但对于 RSA 密钥,该容器的内部数据等于 PKCS#1, 所以可以说对于 RSA 密钥 PKCS#8 是带有额外标头的 PKCS#1,您需要做的就是剥离该额外标头。只需剥离 base64 解码数据的前 26 个字节,即可再次获得 PKCS#1。是的,真的就是这么简单。

要了解有关 PEM 编码中的 PKCS#x 格式的更多信息,请查看此站点。要了解有关ASN.1格式的更多信息,这里有一个很好的网站。如果您需要一个简单但功能强大且交互式的在线 ASN.1 解析器来使用不同的格式,可以直接读取 PEM 数据,以及 base64 和 hexdump 中的 ASN.1,请尝试此站点。

非常重要:将私钥添加到您如上所述创建的密钥链时,请注意此类私钥不包含公钥哈希,但公钥哈希对于他们的钥匙串 API 形成身份很重要 ( SecIdentityRef (,因为使用公钥哈希是 API 找到属于导入证书的正确私钥的方式(SecIdentityRef SecKeyRef只是私钥和证书的SecCertificateRef形成组合对象,它是公钥哈希,将它们绑定在一起(。因此,当您计划将私钥添加到钥匙串时,请务必手动设置公钥哈希,否则您将永远无法为其获取身份,并且无法将钥匙串 API 用于签名或解密数据等任务。公钥哈希必须存储在名为 kSecAttrApplicationLabel 的属性中(我知道这个名字很愚蠢,但它实际上不是一个标签,用户永远看不到任何东西,请查看文档(。例如:

OSStatus error = SecItemAdd(
    (__bridge CFDictionaryRef)@{
        (__bridge NSString *)kSecClass: 
            (__bridge NSString *)kSecClassKey,
        (__bridge NSString *)kSecAttrApplicationLabel: 
             hashOfPublicKey, // hashOfPublicKey is NSData *
#if TARGET_OS_IPHONE
        (__bridge NSString *)kSecValueRef: 
            (__bridge id)privateKeyToAdd, // privateKeyToAdd is SecKeyRef
#else
        (__bridge NSString *)kSecUseItemList: 
              @[(__bridge id)privateKeyToAdd], // privateKeyToAdd is SecKeyRef
              // @[ ... ] wraps it into a NSArray object,
              // as kSecUseItemList expects an array of items
#endif
     },
     &outReference // Can also be NULL,
                   // otherwise reference to added keychain entry
                   // that must be released with CFRelease()
);

在这篇文章的帮助下,经过数小时的努力在线研究,我终于让它完美地工作了。以下是最新版本的 Swift 代码的注释。我希望它可以帮助某人!

  1. 收到夹在标头和尾部之间的 base64 编码字符串中的证书,如下所示(PEM 格式(:

    -----BEGIN CERTIFICATE-----
    -----END CERTIFICATE-----
    
  2. 去除标题和尾部,例如

    // remove the header string  
    let offset = ("-----BEGIN CERTIFICATE-----").characters.count  
    let index = certStr.index(cerStr.startIndex, offsetBy: offset+1)  
    cerStr = cerStr.substring(from: index)  
    // remove the tail string 
    let tailWord = "-----END CERTIFICATE-----"   
    if let lowerBound = cerStr.range(of: tailWord)?.lowerBound {  
    cerStr = cerStr.substring(to: lowerBound)  
    }
    
  3. 将 base64 字符串解码为 NSData:

    let data = NSData(base64Encoded: cerStr, 
       options:NSData.Base64DecodingOptions.ignoreUnknownCharacters)!  
    
  4. 将其从 NSdata 格式转换为 SecCertificate:

    let cert = SecCertificateCreateWithData(kCFAllocatorDefault, data)
    
  5. 现在,此证书可用于与从 urlSession 信任接收的证书进行比较:

    certificateFromUrl = SecTrustGetCertificateAtIndex(...)
    if cert == certificate {
    }
    

最新更新