gpt4 book ai didi

ios - 在 Swift 中将证书添加到 IOS Keychain

转载 作者:可可西里 更新时间:2023-10-31 23:45:08 25 4
gpt4 key购买 nike

我正在尝试将根证书写入我的应用程序钥匙串(keychain),以便我可以与提供自签名证书的服务器通信。

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。

这是我设置钥匙串(keychain)查询的函数

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 做到这一点或有任何建议?

干杯

最佳答案

实际上,我发现了 Adrian 的代码出了什么问题。我找到了这个 link这是来自 Apple 的,非常有用。

要在钥匙串(keychain)中添加证书,我们必须编写以下行:

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")

希望对大家有帮助...

关于ios - 在 Swift 中将证书添加到 IOS Keychain,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27131017/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com