我试图将根证书写入我的应用程序钥匙串,以便我可以与提供自签名证书的服务器通信。
class func setCertificate(certData: NSData, forKey keyName: String) -> Bool
{
var secCert = SecCertificateCreateWithData(kCFAllocatorDefault, certData)
var keychainQueryDictionary: NSMutableDictionary = self.setupKeychainQueryDictionaryForKey(keyName)
keychainQueryDictionary[kSecClassCertificate as NSString] = secCert.takeRetainedValue()
// Protect the keychain entry so it's only valid when the device is unlocked
keychainQueryDictionary[SecAttrAccessible] = kSecAttrAccessibleWhenUnlocked
// Disable icloud sync of keychain data
keychainQueryDictionary[kSecAttrSynchronizable as NSString] = kCFBooleanFalse
let status: OSStatus = SecItemAdd(keychainQueryDictionary, nil)
println(status)
if status == errSecSuccess
{
return true
}
return false
}
但是返回的OSStatus是-50(一个或多个参数传递给一个无效的函数。),我已经尝试了很多演员等但没有到达任何地方。证书绝对有效,因为如果格式存在问题,SecCertificateCreateWithData将返回nil。
这是我设置钥匙串查询的功能
private class func setupKeychainQueryDictionaryForKey(keyName: String) -> NSMutableDictionary
{
// Setup dictionary to access keychain and specify we are using a generic password (rather than a certificate, internet password, etc)
var keychainQueryDictionary: NSMutableDictionary = [SecClass:kSecClassGenericPassword]
// Uniquely identify this keychain accessor
keychainQueryDictionary[SecAttrService] = KeychainManager.serviceName
// Uniquely identify the account who will be accessing the keychain
var encodedIdentifier: NSData? = keyName.dataUsingEncoding(NSUTF8StringEncoding)
keychainQueryDictionary[SecAttrGeneric] = encodedIdentifier
keychainQueryDictionary[SecAttrAccount] = encodedIdentifier
return keychainQueryDictionary
}
有没有人在swift或任何人的建议中这样做?
干杯
答案 0 :(得分:0)
实际上,我发现Adrian的代码出了什么问题。我发现这个来自Apple的link非常有用。
要在钥匙串中添加证书,我们必须写下以下几行:
let secCert = SecCertificateCreateWithData(nil, certInDer as CFData) // certInDer is Certificate(.der) data
var keychainQueryDictionary = [String : Any]()
if let tempSecCert = secCert {
keychainQueryDictionary = [kSecClass as String : kSecClassCertificate, kSecValueRef as String : tempSecCert, kSecAttrLabel as String: "My Certificate"]
}
let summary = SecCertificateCopySubjectSummary(secCert!)! as String
print("Cert summary: \(summary)")
let status = SecItemAdd(keychainQueryDictionary as CFDictionary, nil)
guard status == errSecSuccess else {
print("Error")
return
}
print("success")
希望它能帮助每个人......