Hi I am trying to create identity but I am getting error – Cannot find ‘SecIdentityCreateWithCertificate’ in scope while calling loadIdentity function.
enter image description here
I am not sure what I am doing wrong here. I need to pass identity in https request.
I am using Xcode 15.3 and macOS Sonoma 14.5
import Foundation
import Security
import UIKit
class URLSessionPinningDelegate: NSObject, URLSessionDelegate {
var identity: SecIdentity
init(identity: SecIdentity) {
self.identity = identity
}
func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge, completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Void) {
let credential = URLCredential(identity: self.identity, certificates: nil, persistence: .forSession)
completionHandler(.useCredential, credential)
}
}
func loadIdentity(certPath: String, keyPath: String) -> SecIdentity? {
guard let certData = try? Data(contentsOf: URL(fileURLWithPath: certPath)) else {
print("Unable to load certificate")
return nil
}
guard let cert = SecCertificateCreateWithData(nil, certData as CFData) else {
print("Unable to create certificate")
return nil
}
guard let keyData = try? Data(contentsOf: URL(fileURLWithPath: keyPath)) else {
print("Unable to load private key")
return nil
}
let keyDict: [NSString: Any] = [
kSecAttrKeyType: kSecAttrKeyTypeRSA,
kSecAttrKeyClass: kSecAttrKeyClassPrivate,
kSecAttrKeySizeInBits: 2048,
kSecReturnPersistentRef: true
]
var error: Unmanaged<CFError>?
guard let privateKey = SecKeyCreateWithData(keyData as CFData, keyDict as CFDictionary, &error) else {
print("Unable to create private key")
return nil
}
var identity: SecIdentity?
let status = SecIdentityCreateWithCertificate(cert, privateKey, &identity)
guard status == errSecSuccess else {
print("Unable to create identity")
return nil
}
return identity
}
@objc(AzureProvisionWithCertificate)
class AzureProvisionWithCertificate: NSObject { @objc(provisionAndUploadFile:withRegistrationId:withKey:withCertificate:withProvisionHost:withFileNameWithFolder:withModelId:withResolver:withRejecter:)
func provisionAndUploadFile(scopeId:String, registrationId:String, key:String, certificate:String, provisionHost:String, fileNameWithFolder:String, modelId:String, resolve:@escaping RCTPromiseResolveBlock, reject:@escaping RCTPromiseRejectBlock) -> Void {
let certPath = "/path/to/your/device-cert.pem"
let keyPath = "/path/to/your/device-key.pem"
guard let identity = loadIdentity(certPath: certificate, keyPath: key) else {
print("Unable to load identity")
return
}
let session = URLSession(configuration: .default, delegate: URLSessionPinningDelegate(identity: identity), delegateQueue: nil)
guard let url = URL(string: "https://global.azure-devices-provisioning.net/[scopeId]/registrations/[registrationId]/register?api-version=2021-06-01") else {
print("Invalid URL")
return
}
var request = URLRequest(url: url)
//Https request code here
}
}