【问题标题】:Getting public key information from a certificate file in iOS app [closed]从 iOS 应用程序中的证书文件获取公钥信息 [关闭]
【发布时间】:2015-02-15 20:42:07
【问题描述】:

我正在开发一个与远程 API 通信的 iOS 应用程序。此 API 要求我使用存储在 .cer 文件中的公钥加密数据(由 Windows 机器上的 OpenSSL 生成)。我已经在我的项目中包含了.cer 文件,并且我正在使用以下代码来获取证书参考(至少我认为我是这样做的)。

NSBundle *bundle = [NSBundle bundleForClass:[self class]];
NSData *iosTrustedCertDerData = [NSData dataWithContentsOfFile:[bundle pathForResource:@"CertName" ofType:@"cer"]];
SecCertificateRef certificate = SecCertificateCreateWithData(NULL, (__bridge CFDataRef) iosTrustedCertDerData);

在那之后我几乎陷入了困境。我已经在网上搜索了一段时间,看到各种对 openssl.h 的引用。但是,openssl 似乎只适用于 Mac,而不适用于 iOS。

我不禁想知道为什么我找不到任何在您的 iOS 应用程序中使用证书的示例。每次我在 iOS 应用中搜索证书时,我都会得到解释配置文件等的结果。这不是我想要的。

我找到了 RNCryptor,但据我所知,它是一个用于加密/解密的库,但不支持从证书中读取密钥。

我正在寻找有关如何使用存储在证书中的公钥的库(或代码示例),该证书包含在应用程序中。 有些东西告诉我我走错了路。

当我能够从证书文件中获取密钥时,加密不会成为问题......希望如此。

任何帮助将不胜感激!

【问题讨论】:

    标签: ios encryption certificate key public


    【解决方案1】:

    我已经在 iOS 安全框架上工作了好几个星期了。没有足够的代码示例来实际实现安全框架中的许多功能。

    在您获得对证书的引用后,SecCertificateCopyPublicKey 在 iOS SDK 8.2 中不可用,但您可以使用前向声明进行调用。但这对我不起作用。

    最后,这里是加载证书、获取证书数据引用、创建 X509 策略对象并使用 SecTrust*() 函数获取公钥引用的解决方案。获得公钥后,您可以进行加密。 注意 - 此代码已在 XCode 版本 6.2 (6C131e) 和 iOS SDK 8.2 上测试

    //1. Load certificate from main bundle
    NSString *thePath = [[NSBundle mainBundle]
                         pathForResource:@"myTest" ofType:@"cer"];
    
    //2. Get the contents of the certificate and load to NSData
    NSData *certData = [[NSData alloc]
                        initWithContentsOfFile:thePath];
    
    //3. Get CFDataRef of the certificate data
    CFDataRef myCertData = (__bridge CFDataRef)certData;
    
    SecCertificateRef myCert;
    SecKeyRef aPublicKeyRef = NULL;
    SecTrustRef aTrustRef = NULL;
    
    //4. Create certificate with the data
    myCert = SecCertificateCreateWithData(NULL, myCertData);
    
    //5. Returns a policy object for the default X.509 policy
    SecPolicyRef aPolicyRef = SecPolicyCreateBasicX509();
    
    if (aPolicyRef) {
        if (SecTrustCreateWithCertificates((CFTypeRef)myCert, aPolicyRef, &aTrustRef) == noErr) {
            SecTrustResultType result;
            if (SecTrustEvaluate(aTrustRef, &result) == noErr) {
                //6. Returns the public key for a leaf certificate after it has been evaluated.
                aPublicKeyRef = SecTrustCopyPublicKey(aTrustRef);
            }
        }
    }
    
    NSLog(@"%@", aPublicKeyRef);
    

    【讨论】:

      猜你喜欢
      • 2011-03-24
      • 2022-10-19
      • 1970-01-01
      • 1970-01-01
      • 2010-10-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多