Skip to content

Instantly share code, notes, and snippets.

@algal

algal/PKCS12.swift

Last active Oct 7, 2020
Embed
What would you like to do?
Reading PKCS12 with Swift in Foundation
// xcode 7.3
import Foundation
/**
Struct representing values returned by `SecPKCS12Import` from the Security framework.
This is what Cocoa and CocoaTouch can tell you about a PKCS12 file.
*/
public class PKCS12 {
let label:String?
let keyID:NSData?
let trust:SecTrustRef?
let certChain:[SecTrustRef]?
let identity:SecIdentityRef?
public init(PKCS12Data:NSData,password:String)
{
let importPasswordOption:NSDictionary = [kSecImportExportPassphrase as NSString:password]
var items : CFArray?
let secError:OSStatus = SecPKCS12Import(PKCS12Data, importPasswordOption, &items)
guard secError == errSecSuccess else {
if secError == errSecAuthFailed {
NSLog("ERROR: SecPKCS12Import returned errSecAuthFailed. Incorrect password?")
}
fatalError("SecPKCS12Import returned an error trying to import PKCS12 data")
}
guard let theItemsCFArray = items else { fatalError() }
let theItemsNSArray:NSArray = theItemsCFArray as NSArray
guard let dictArray = theItemsNSArray as? [[String:AnyObject]] else { fatalError() }
func f<T>(key:CFString) -> T? {
for d in dictArray {
if let v = d[key as String] as? T {
return v
}
}
return nil
}
self.label = f(kSecImportItemLabel)
self.keyID = f(kSecImportItemKeyID)
self.trust = f(kSecImportItemTrust)
self.certChain = f(kSecImportItemCertChain)
self.identity = f(kSecImportItemIdentity)
}
}
extension NSURLCredential {
public convenience init?(PKCS12 thePKCS12:PKCS12) {
if let identity = thePKCS12.identity {
self.init(
identity: identity,
certificates: thePKCS12.certChain,
persistence: NSURLCredentialPersistence.ForSession)
}
else { return nil }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.