1

I am having trouble while using SecItemCopyMatching function.

Our function works nearly all devices except only iPhone 13 Pro Max devices.

I searched a lot and found some posts similar to this issue.

People come up with this open source library however I still could not make it work. https://www.hackingwithswift.com/read/28/3/writing-somewhere-safe-the-ios-keychain (https://stackoverflow.com/a/58233542/5528870) They say that they have found the solution via that KeychainWrapper but I could not find the correct way to make it work.

This is our code snippet which works on most of devices except only iPhone 13 Pro Max devices:

  func signString(clearString:String) -> Bool {
    let getquery: [String: Any] = [kSecClass as String: kSecClassKey,
                                   kSecAttrApplicationTag as String: serviceName,
                                   kSecAttrKeyType as String: kSecAttrKeyTypeECSECPrimeRandom,
                                   kSecReturnRef as String: true]
    
    var item: CFTypeRef?
    let status = SecItemCopyMatching(getquery as CFDictionary, &item)
    
    if (status != errSecSuccess) {
        print("No key found")
        return false
    }
    else {
        let key = item as! SecKey
        self.privateKey = key
        print("key = ",key)
        let data = clearString.data(using: .utf8)! as CFData
        let algorithm: SecKeyAlgorithm = .ecdsaSignatureMessageX962SHA256
        
        if (self.privateKey != nil) {
            guard SecKeyIsAlgorithmSupported(self.privateKey!, .sign, algorithm) else 
            {
                print("Algorithm Not Supported")
                return false
            }
            
            var error: Unmanaged<CFError>?
            guard let signature = SecKeyCreateSignature(self.privateKey!,algorithm, data, &error) as Data? else {
                print("signature error")
                return false
            }
            
            self.signedString = signature.base64EncodedString()
            return true
        }
        else {
            print("Private Key is null")
            return false
        }
    }
}

I have tried to use many key combinations. However it never returned errSecSuccess.

Sorry for my lack of information about this topic.

I want to adjust my query so that it can work on all devices.. Thanks in advance

Hilal
  • 902
  • 2
  • 22
  • 47
  • 1
    _it never returned errSecSuccss_ But what does it return? You can also use `SecCopyErrorMessageString(status, nil)` to extract, hopefully, some more info about the status code. Also, sanity check, are you sure it's stored? How do you know? – Bram Sep 14 '22 at 15:06

0 Answers0