1

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.)
Ramis
  • 13,985
  • 7
  • 81
  • 100
  • I met same issue code status is -25299(The item already exists). I try a lot. Finally, I get the key-chain is unique-code. It can't update. If you want to update, you need to delete it first. Thanks for this ticket. – Phineas Huang Aug 09 '18 at 09:43

1 Answers1

1

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
        ]
Ramis
  • 13,985
  • 7
  • 81
  • 100