When trying to add second certificate fails with -25299 (The item already exists.). They have different kSecAttrLabel. Before trying to delete it fails as well with code -25300 (The item cannot be found.).
Maybe someone knows what is wrong with this code? Did I miss some attributes?
if let cer1 = "cert1".dataUsingEncoding(NSUTF8StringEncoding),
let cer2 = "cert2".dataUsingEncoding(NSUTF8StringEncoding) {
addCertificate(cer1, label: "TestCertificate_1")
addCertificate(cer2, label: "TestCertificate_2")
}
func addCertificate(certificate: NSData, label: String) {
let query = [
String(kSecClass) : kSecClassCertificate,
String(kSecAttrLabel) : label,
String(kSecValueData) : certificate
]
var status = SecItemDelete(query)
if status != noErr {
print("Error deleting cer from keychain. Error: \(status)")
}
status = SecItemAdd(query, nil)
if status != noErr {
print("Error adding cer to keychain. Error: \(status)")
}
}
// Output:
// Error deleting cer from keychain. Error: -25300 (The item cannot be found.)
// Error deleting cer from keychain. Error: -25300 (The item cannot be found.)
// Error adding cer to keychain. Error: -25299 (The item already exists.)
For a keychain item of class kSecClassCertificate, the primary key is the combination of kSecAttrCertificateType, kSecAttrIssuer and kSecAttrSerialNumber.
let query = [
String(kSecClass) : kSecClassCertificate,
String(kSecAttrLabel) : label,
String(kSecValueData) : certificate,
String(kSecAttrSerialNumber) : serialNumber
]