是否可以通过“始终信任”以编程方式在钥匙串访问中安装“不受信任的证书”或“ P12”文件?

时间:2018-08-03 10:33:39

标签: macos keychain

我是Mac的钥匙串访问的新手。 我只需要在Mac中以编程方式在“钥匙串访问”中以“始终信任”方式安装Untrused证书或P12文件。

我正在使用以下代码:

 -(void)addCertificate
  {
    NSData *PKCS12Data = [[NSData alloc] initWithContentsOfFile:
   @"/Users/Desktop/Certificates.p12"];

    CFDataRef inPKCS12Data = (__bridge CFDataRef)PKCS12Data;
    CFStringRef password = (CFStringRef)@"";
    const void *keys[] = { kSecImportExportPassphrase };
    const void *values[] = { password };

    CFDictionaryRef optionsDictionary = CFDictionaryCreate(NULL, keys, 
    values, 1, NULL, NULL);

    CFArrayRef items = CFArrayCreate(NULL, 0, 0, NULL);
    SecCertificateRef rootCert = 
    SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef) 
    inPKCS12Data);

    OSStatus securityError = SecPKCS12Import(inPKCS12Data, 
    optionsDictionary, &items);

    if (securityError == 0) {
         NSLog(@" *** Certificate install Success ***");
    } else {
      NSLog(@" *** Certificate install Failure ***");
    }


    OSStatus err = noErr;
    CFTypeRef result;
    NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
                      (__bridge id)kSecClassCertificate, kSecClass,
                      rootCert, kSecValueRef,
                      nil];

    err = SecItemAdd((__bridge CFDictionaryRef)dict, &result);
    if(err!=noErr) NSLog(@"error while importing");

    if (err==errSecDuplicateItem) NSLog(@"Cert already installed");
    NSLog(@":%i",(int)err);
    assert(err==noErr||err==errSecDuplicateItem);   
   // accept no errors other than duplicate

   err = noErr;
   SecTrustRef trust;

   err = SecTrustCreateWithCertificates(rootCert, 
      SecPolicyCreateBasicX509() ,&trust);

   assert(err==noErr);
   err = noErr;

   CFMutableArrayRef newAnchorArray = 
   CFArrayCreateMutable(kCFAllocatorDefault,0,&kCFTypeArrayCallBacks);

   CFArrayAppendValue(newAnchorArray,rootCert);

   err = SecTrustSetAnchorCertificates(trust, newAnchorArray);
   assert(err==noErr);

   SecTrustResultType trustResult;
   err=SecTrustEvaluate(trust,&trustResult);
   assert(err==noErr);
   rootCert=nil;   // Done with the policy object

 }

通过使用此代码,我们仅添加证书 请帮助我摆脱困境...

0 个答案:

没有答案