Create Identity from certificate and key

I have x509 certificate in pem format. CertificatePem

-----BEGIN CERTIFICATE----- MIIC3jCCAcYCAQAw...9gBFNQUdahSccXF2bnZkv2Kh -----END CERTIFICATE-----

PrivatekeyPem:

-----BEGIN RSA PRIVATE KEY----- MIIEowIBAAKCAQE...ooxp1Nyl17zfP -----END RSA PRIVATE KEY-----

And I convert it to base64 using this JS code


  const pemHeader = type === 'certificate'? '-----BEGIN CERTIFICATE-----' : '-----BEGIN RSA PRIVATE KEY-----';

  const pemFooter = type === 'certificate'? '-----END CERTIFICATE-----':'-----END RSA PRIVATE KEY-----';

let base64Key = pemKey.replace(pemHeader, '').replace(pemFooter, '');

// Remove any newline characters
  base64Key = base64Key.replace(/\r?\n|\r/g, '');
  return base64Key;
};

And my CertificateBase64 look like:

MIIC3jCCAcYCAQAw...9gBFNQUdahSccXF2bnZkv2Kh

PrivateBase64:

MIIEowIBAAKCAQE...ooxp1Nyl17zfP

I want to create identity to use in https request. I am getting error:

Unable to create identity: -25300

My loadIdentity function look like this:

func loadIdentity(certificate: String, privateKey: String) -> SecIdentity? {
    print("privateKey: \(privateKey)")

    guard let certData = Data(base64Encoded: certificate) else {
        print("Unable to decode certificate PEM")
        return nil
    }
    print("certData: \(certData)")

// Create certificate object
    guard let cert = SecCertificateCreateWithData(nil, certData as CFData) else {
        print("Unable to create certificate")
        return nil
    }
      // Add certificate to the keychain
    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 decode private key PEM")
        return nil
    }
    print("keyData: \(keyData)")

   // Define attributes for the private key
    let keyDict: [NSString: Any] = [
        kSecAttrKeyType: kSecAttrKeyTypeRSA,
        kSecAttrKeyClass: kSecAttrKeyClassPrivate,
        kSecAttrKeySizeInBits: 2048,
        kSecReturnPersistentRef: true
    ]

//    Create private key object
    var error: Unmanaged<CFError>?
    guard let privateKeyData = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, &error) else {
        // print("Unable to create private key: \(error?.takeRetainedValue() ?? "Unknown error" as CFError)")
        print("Unable to create private key")
        return nil
    }

        // Add private key to the keychain
    let keyAddQuery: [NSString: Any] = [
        kSecClass: kSecClassKey,
        kSecValueRef: privateKeyData,
        kSecAttrLabel: "myPrivateKey",
        kSecAttrAccessible: kSecAttrAccessibleWhenUnlocked
    ]
    status = SecItemAdd(keyAddQuery as CFDictionary, nil)
    if status != errSecSuccess && status != errSecDuplicateItem {
        print("Failed to add private key to keychain: \(status)")
        return nil
    }
    
        // Query to retrieve the identity from the keychain
    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)
    
}

If you widen your identity query — that is, remove the kSecAttrLabel and kSecMatchItemList and set kSecMatchLimit to kSecMatchLimitAll — do you get any identities back from the keychain?

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Create Identity from certificate and key
 
 
Q