我正在开发一个需要在远程服务器上执行HTTPS POST的iOS应用。这是我想做的:
// How to initialize 'credential' with a certificate.der (or .pem)
var credential: URLCredential?
let pms: [String: Any] = ["func": "os.getpid"]
Alamofire.request("https://mytestdomain.mycom/exec", method: .post,
parameters: pms, encoding: JSONEncoding.default, headers: nil)
.authenticate(usingCredential: credential!)
.responseJSON { response in
if response.result.isSuccess {
print("Success")
}
else {
print("Error")
}
但是我还没有找到使用证书初始化证书的方法。可能吗?
答案 0 :(得分:0)
我不了解DER或PEM ..但是对于p12,您可以:
private func loadCertificate(name: String, password: String?) throws -> (identity: SecIdentity, certificate: SecCertificate) {
let path = Bundle.main.path(forResource: name, ofType: "p12")!
let data = NSData(contentsOfFile: path)!
let certificate = SecCertificateCreateWithData(nil, data)!
let options = [String(kSecImportExportPassphrase):password ?? ""]
var items: CFArray? = nil
let result = SecPKCS12Import(data, options as CFDictionary, &items)
if (result != errSecSuccess) {
throw RuntimeError("Cannot Import Certificte")
}
let info = (items! as NSArray).firstObject! as! NSDictionary
let identity = info[String(kSecImportItemIdentity)] as! SecIdentity
return (identity, certificate)
}
然后:
let info = try loadCertificate(name: "MyCertificate", password: "Password..")
let credentials = URLCredential(identity: info.identity, certificates: [info.certificate], persistence: .forSession)