如何将自己的根证书颁发机构(CA)文件添加到Swift中设备的根CA列表中?
我正在尝试将下面的Objective-C代码转换为Swift,但我不知道如何为这种情况正确编写字典。
夫特:
let rootCertPath = NSBundle.mainBundle().pathForResource("server", ofType: "crt")!
let rootCertData = NSData(contentsOfFile: rootCertPath)
let rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, rootCertData)
// Error: '_' is not convertible to 'CFStringRef'
let dict =
[
kSecClass: kSecClassCertificate,
kSecValueRef: rootCert
] as CFDictionaryRef
error = SecItemAdd(dict, result)
目标-C:
NSString *rootCertPath = [[NSBundle mainBundle] pathForResource:@"server" ofType:@"crt"];
NSData *rootCertData = [NSData dataWithContentsOfFile:rootCertPath];
OSStatus err = noErr;
SecCertificateRef rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, (CFDataRef) rootCertData);
CFTypeRef result;
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
(id)kSecClassCertificate, kSecClass,
rootCert, kSecValueRef,
nil];
err = SecItemAdd((CFDictionaryRef)dict, &result);
if( err == noErr) {
NSLog(@"Install root certificate success");
} else if( err == errSecDuplicateItem ) {
NSLog(@"duplicate root certificate entry");
} else {
NSLog(@"install root certificate failure");
}
答案 0 :(得分:1)
我找到了一个似乎有效的解决方案,但我不完全确定它是否是正确的方法。如果我错了,请纠正我。
首先,我需要将证书从* .crt转换为* .der,因为它一直在创建一个零SecCertificate。
openssl x509 -in server.crt -out server.der -outform DER
我的代码:
func installRootCertificate() -> Bool
{
var result: UnsafeMutablePointer<Unmanaged<AnyObject>?> = nil
var error = noErr
let rootCertPath = NSBundle.mainBundle().pathForResource("server", ofType: "der")!
let rootCertData = NSData(contentsOfFile: rootCertPath)!
let rootCert = SecCertificateCreateWithData(kCFAllocatorDefault, rootCertData)
let kSecClassValue = NSString(format: kSecClass)
let kSecClassCertificateValue = NSString(format: kSecClassCertificate)
let kSecValueRefValue = NSString(format: kSecValueRef)
let dict =
[
kSecClassValue: kSecClassCertificateValue,
kSecValueRefValue: rootCert.takeRetainedValue()
] as CFDictionaryRef
error = SecItemAdd(dict, result)
if(error == noErr)
{
println("Installed root certificate successfully");
return true
}
else if(error == errSecDuplicateItem)
{
println("Duplicate root certificate entry");
}
else
{
println("Install root certificate failure")
}
return false
}