Retrieve public and private key pair from keychain

We are trying to retrieve a certificate and private key pair from keychain .  These may not be generated locally on the Mac machine but added to the keychain by some MDM product like Jamf etc.  Initially I tried to retrieve using identity,  but  couldn’t search with identity, and as per the notes from other discussions, how the identity is calculated is different in Mac OS,  so I couldn’t retrieve it.

Then I tried to retrieve the key first,  but even for that, I couldn’t see any attributes I can use to select specific parameter like issued by etc. So I tried to retrieve one seckeyref object and use it as shown below


 [queryPrivateKey setObject:(id)kSecClassKey forKey:(id)kSecClass];

 [queryPrivateKey setObject:(id)kSecAttrKeyTypeRSA forKey:(id)kSecAttrKeyType];

 [queryPrivateKey setObject:[NSNumber numberWithBool:YES] forKey:(id)kSecReturnRef];

  

 sanityCheck = SecItemCopyMatching((CFDictionaryRef)queryPrivateKey, (CFTypeRef *)&privateKeyReference);

 
 if (sanityCheck != noErr)

 {

     privateKeyReference = NULL;

     return;

 }

  
signedHashBytesSize = SecKeyGetBlockSize(privateKeyReference);

SecKeyRef publicKey = SecKeyCopyPublicKey(privateKeyReference);

And signedHashBytesSize is showing as 256 and publicKey is also not null, but I couldn’t export any of the above using SecItemExport or convert private key to NSData using SecKeyCopyExternalRepresentation etc.

So could you please let me know how to search for a specific identity or a specific key, from which we can export both public key and private key in some openssl format so that this can be used to sign.