Getting error while creating identity from certificate and key

I am trying to create identity from certificate and private key which are in base64 format.

I am getting error - Unable to create identity

one time I get the error - Failed to add certificate and private key to keychain: -26276

My Xcode is 15.3 and macOS is Sonoma 14.5

func loadIdentity(certificate: String, privateKey: String) -> SecIdentity? {
    guard let certData = Data(base64Encoded: certificate) else {
        print("Unable to encode certificate base64")
        return nil
    }
    guard let cert = SecCertificateCreateWithData(nil, certData as CFData) else {
        print("Unable to create certificate")
        return nil
    }
    let certAddQuery: [NSString: Any] = [
        kSecClass: kSecClassCertificate,
        kSecValueRef: cert,
        kSecAttrLabel: "myCertificate"
    ]
    var status = SecItemAdd(certAddQuery as CFDictionary, nil)
    if status != errSecSuccess && status != errSecDuplicateItem {
        print("Failed to add certificate to keychain: \(status)")
        return nil
    }
    guard let keyData = Data(base64Encoded: privateKey) else {
        print("Unable to encode private key base64")
        return nil
    }
    let keyDict: [NSString: Any] = [
        kSecAttrKeyType: kSecAttrKeyTypeRSA,
        kSecAttrKeyClass: kSecAttrKeyClassPrivate,
        kSecAttrKeySizeInBits: 2048,
        kSecReturnPersistentRef: true
    ]

    var error: Unmanaged<CFError>?
    guard let privateKeyData = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, &error) else {
        print("Unable to create private key")
        return nil
    }
    let keyAddQuery: [NSString: Any] = [
        kSecClass: kSecClassKey,
        kSecValueRef: privateKeyData,
        kSecAttrLabel: "myKey",
        kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked
    ]
    status = SecItemAdd(keyAddQuery as CFDictionary, nil)
    if status != errSecSuccess && status != errSecDuplicateItem {
        print("Failed to add private key to keychain: \(status)")
        return nil
    }
        let identityQuery: [NSString: Any] = [
        kSecClass: kSecClassIdentity,
        kSecReturnRef: true,
        kSecAttrLabel: "myCertificate",
        kSecMatchItemList: [cert, privateKeyData]
    ]
    
    var identity: CFTypeRef?
    status = SecItemCopyMatching(identityQuery as CFDictionary, &identity)
    
     guard status == errSecSuccess else {
         print("Unable to create identity")
         return nil
     }
    return (identity as! SecIdentity)
    
}
Getting error while creating identity from certificate and key
 
 
Q