2017-02-24 112 views
11

以下代码读出macOS中的根证书。以编程方式读取iOS中的根CA证书

我只是想知道iOS中的等效代码是什么?

https://github.com/HaxeFoundation/hxcpp/blob/7bd5ff3/src/hx/libs/ssl/SSL.cpp#L455-L491

CFMutableDictionaryRef search; 
CFArrayRef result; 
SecKeychainRef keychain; 
SecCertificateRef item; 
CFDataRef dat; 
sslcert *chain = NULL; 

// Load keychain 
if(SecKeychainOpen("/System/Library/Keychains/SystemRootCertificates.keychain",&keychain) != errSecSuccess) 
    return null(); 

// Search for certificates 
search = CFDictionaryCreateMutable(NULL, 0, NULL, NULL); 
CFDictionarySetValue(search, kSecClass, kSecClassCertificate); 
CFDictionarySetValue(search, kSecMatchLimit, kSecMatchLimitAll); 
CFDictionarySetValue(search, kSecReturnRef, kCFBooleanTrue); 
CFDictionarySetValue(search, kSecMatchSearchList, CFArrayCreate(NULL, (const void **)&keychain, 1, NULL)); 
if(SecItemCopyMatching(search, (CFTypeRef *)&result) == errSecSuccess){ 
    CFIndex n = CFArrayGetCount(result); 
    for(CFIndex i = 0; i < n; i++){ 
     item = (SecCertificateRef)CFArrayGetValueAtIndex(result, i); 

     // Get certificate in DER format 
     dat = SecCertificateCopyData(item); 
     if(dat){ 
      if(chain == NULL){ 
       chain = new sslcert(); 
       chain->create(NULL); 
      } 
      mbedtls_x509_crt_parse_der(chain->c, (unsigned char *)CFDataGetBytePtr(dat), CFDataGetLength(dat)); 
      CFRelease(dat); 
     } 
    } 
} 
CFRelease(keychain); 
if(chain != NULL) 
    return chain; 
+0

由于您显示的代码是用'cpp'编写的,所以您仍然可以直接使用它,因为cpp中使用的所有关键字都来自Apple的'Security.framework',您是否尝试过使用相同的内容,您可以使用整个'SSL.cpp'?我认为它会为你工作。 – iphonic

+0

'/ System/Library/Keychains/SystemRootCertificates.keychain'在iOS上不存在。或者至少你不能读它,因为一切都是沙盒。 – KevinResoL

回答

3

恐怕是不可能做到给出的应用生态系统中的iOS等效是沙箱。

不知道您的目的,解决此问题的常用方法是从apple.com/certificateauthority下载苹果根证书,然后将其存储在您的应用中以供阅读。

看看这个article也鼓舞你。

PS:如果iOS设备已越狱,可能会这样做。

+0

目的是在iOS中使用mbedtls(以前称为PolarSSL)。因为mbedtls需要根CA来运行。发布的macOS代码确实如此。 – KevinResoL

+0

[他们](https://github.com/robotmedia/RMStore/blob/master/RMStore/Optional/RMAppReceipt.m#L247)正在做类似的事情。这可能会激励你。作为选项,您可以将其转换为DER格式以防万一。 – Ricowere

+0

该示例仅从互联网下载一个根证书(Apple版本),或将其捆绑到应用程序中。所以它与我的要求完全不同。 (我需要存储在设备本身中的所有根证书) – KevinResoL

2

Security.framework函数SecTrustCopyAnchorCertificates允许您检索存储在系统中的根证书仅在macOS上可用。奇怪的是,它是iOS上不可用的少数函数之一(来自相关函数集)。故意,谁知道?

+0

对不起,我不太明白。我的代码没有使用'SecTrustCopyAnchorCertificates',所以我不确定你为什么提到它。或者换句话说,你的意思是说我的原始问题根本没有解决方案,因为有些API只是在iOS上不可用? – KevinResoL

+0

是的。在macOS上,有不同的方法来检索系统中的根证书。由于iOS的沙盒限制,您的问题中的代码片段无法在iOS上运行。 'SecTrustCopyAnchorCertificates'和'SecTrustSettingsCopyCertificates'是应该让你能够在iOS上检索根证书的两个函数;但无论出于什么原因,它们都不适用于iOS。 –

相关问题