gpt4 book ai didi

ios - 使用客户端证书对 Alamofire 进行身份验证

转载 作者:行者123 更新时间:2023-11-28 07:40:00 24 4
gpt4 key购买 nike

我正在开发需要在远程服务器上执行 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")
}

但是我还没有找到用证书初始化凭据的方法。是否可以?

最佳答案

我不知道 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)

关于ios - 使用客户端证书对 Alamofire 进行身份验证,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52546674/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com