在iOS Swift中添加SSL证书

时间:2018-08-09 12:13:31

标签: ios swift xcode ssl-certificate

请告诉我如何在ios swift 4中验证或添加ssl证书。如何从服务器验证证书是否受信任。请告诉我如何逐步完成该完整过程

这是我请求服务器的代码:

let soapMessage = "<?xml version='1.0' encoding='utf-8'?><soap:Envelope xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance' xmlns:xsd='http://www.w3.org/2001/XMLSchema' xmlns:soap='http://schemas.xmlsoap.org/soap/envelope/'><soap:Body><GetLeaveApprove xmlns='http://tempuri.org/'><Token>\(token)</Token><ReferenceNo>\(ReferenceNo)</ReferenceNo><Stage>\(Stage)</Stage><Action>\(Action)</Action><Remarks>\(remarks)</Remarks></GetLeaveApprove></soap:Body></soap:Envelope>"

    let urlString = URL(string:"https://in.megasoftsol.com/ehrms.test/HRMSServices.asmx")

    let theRequest = NSMutableURLRequest(url: urlString!)
    let msgLength: String = "\(soapMessage.count)"
    theRequest.addValue("in.megasoftsol.com", forHTTPHeaderField: "Host")
    theRequest.addValue("text/xml; charset=utf-8", forHTTPHeaderField: "Content-Type")

    theRequest.addValue(msgLength, forHTTPHeaderField: "Content-Length")
    theRequest.httpMethod = "POST"
    theRequest.httpBody = soapMessage.data(using: String.Encoding.utf8)

    let connection = NSURLConnection(request: theRequest as URLRequest, delegate: self)

    if (connection != nil)
    {
        webResponseData = self.webResponseData as Data
        print("\(webResponseData)")
        connection?.start()
    }

1 个答案:

答案 0 :(得分:0)

如果不通过服务器则创建证书

openssl s_client -showcerts -connect www.infinum.co:443 infinumco.cer

使用SWIFT和ALAMOFIRE进行固定确保您使用会话管理器引用并将其用于您的请求。

    let serverTrustPolicies: [String: ServerTrustPolicy] = [
    "infinum.co": .pinPublicKeys(
        publicKeys: ServerTrustPolicy.publicKeys(),
        validateCertificateChain: true,
        validateHost: true
    )
]

let sessionManager = SessionManager( // Make sure you keep a reference of this guy somewhere
    serverTrustPolicyManager: ServerTrustPolicyManager(
        policies: serverTrustPolicies
    )
)

所有内容均与默认固定实现完全相同,只是现在需要使用此类来代替。

import UIKit
import Alamofire

class CustomServerTrustPolicyManager: ServerTrustPolicyManager {

    override func serverTrustPolicy(forHost host: String) -> ServerTrustPolicy? {
        // Check if we have a policy already defined, otherwise just kill the connection
        if let policy = super.serverTrustPolicy(forHost: host) {
            print(policy)
            return policy
        } else {
            return .customEvaluation({ (_, _) -> Bool in
                return false
            })
        }
    }

}

您可以固定证书:

if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0) {
    let serverCertificateData = SecCertificateCopyData(serverCertificate) as Data

    if pinnedCertificates().contains(serverCertificateData) {
        completionHandler(.useCredential, URLCredential(trust: trust))
        return
    }
}

或公共密钥:

// Or, compare the public keys
if let serverCertificate = SecTrustGetCertificateAtIndex(trust, 0), let serverCertificateKey = publicKey(for: serverCertificate) {
    if pinnedKeys().contains(serverCertificateKey) {
        completionHandler(.useCredential, URLCredential(trust: trust))
        return
    }
}