簡體   English   中英

Swift 3如何使用SSL Pinning和AlamoFire驗證服務器證書?

[英]Swift 3 How to validate server certificate using SSL Pinning and AlamoFire?

我正在用Swift 3編寫一個需要與服務器對話的應用程序。 我擁有der和crt格式的完整證書鏈,這是我的CA(請勿與自簽名混淆)。 如何在我的應用程序中使用它來驗證服務器? 以下是我的休息電話和回復

休息電話:

var request = URLRequest(url: URL(string: "https://myserver/login")!)
    request.addValue("Content-Type", forHTTPHeaderField: "application/json")
    request.httpMethod = "GET"
    let session = URLSession.shared

    session.dataTask(with: request) {data, response, err in         
        print("=========================DATA===============================")
        if data != nil {
            print(data!)
        }
        print("=========================RESPONSE===============================")
        if response != nil {
            print(response!)
        }
        print("=========================ERR===============================")
        if err != nil {
            print(err!)
        }
        }.resume()

輸出:

=========================DATA===============================
=========================RESPONSE===============================
=========================ERR===============================
Error Domain=NSURLErrorDomain Code=-1200 "An SSL error has occurred and a secure connection to the server cannot be made." UserInfo={NSURLErrorFailingURLPeerTrustErrorKey=<SecTrustRef: 0x60800011f020>, NSLocalizedRecoverySuggestion=Would you like to connect to the server anyway?, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, NSErrorPeerCertificateChainKey=(
"<cert(0x7fae4803d200) s: myserver i: MySubCA>",
"<cert(0x7fae48047000) s: MySubCA i: MyRootCA>",
"<cert(0x7fae48044600) s: MyRootCA i: MyRootCA>"
), NSUnderlyingError=0x60800005a040 {Error Domain=kCFErrorDomainCFNetwork Code=-1200 "(null)" UserInfo={_kCFStreamPropertySSLClientCertificateState=0, kCFStreamPropertySSLPeerTrust=<SecTrustRef: 0x60800011f020>, _kCFNetworkCFStreamSSLErrorOriginalValue=-9802, _kCFStreamErrorDomainKey=3, _kCFStreamErrorCodeKey=-9802, kCFStreamPropertySSLPeerCertificates=(
"<cert(0x7fae4803d200) s: myserver i: MySubCA>",
"<cert(0x7fae48047000) s: MySubCA i: MyRootCA>",
"<cert(0x7fae48044600) s: MyRootCA i: MyRootCA>"
)}}, NSLocalizedDescription=An SSL error has occurred and a secure connection to the server cannot be made., NSErrorFailingURLKey=https://myserver/login, NSErrorFailingURLStringKey=https://myserver/login, NSErrorClientCertificateStateKey=0}

我很簡單地利用了在線博客AlamoFire和openssl解決了該問題。

我將AlamoFire用於iOS上的網絡。

我用一篇有關iOS上的SSL固定的文章來指出正確的方向。

我使用openssl將我的證書轉換為der格式。

通過openssl Der轉換。

openssl x509 -in cert.crt -out cert.der -outform DER

您將需要將der格式的證書添加到您的應用程序包中。

Swift 3實施

// Your hostname and endpoint
let hostname = "YOUR_HOST_NAME"
let endpoint = "YOUR_ENDPOINT"
let cert = "YOUR_CERT" // e.g. for cert.der, this should just be "cert"

// Set up certificates
let pathToCert = Bundle.main.path(forResource: cert, ofType: "der")
let localCertificate = NSData(contentsOfFile: pathToCert!)
let certificates = [SecCertificateCreateWithData(nil, localCertificate!)!]

// Configure the trust policy manager
let serverTrustPolicy = ServerTrustPolicy.pinCertificates(
    certificates: certificates,
    validateCertificateChain: true,
    validateHost: true
)    
let serverTrustPolicies = [hostname: serverTrustPolicy]
let serverTrustPolicyManager = ServerTrustPolicyManager(policies: serverTrustPolicies)

// Configure session manager with trust policy
afManager = SessionManager(
    configuration: URLSessionConfiguration.default,
    serverTrustPolicyManager: serverTrustPolicyManager
)


afManager.request(endpoint, method: .get).responseJSON { response in
    debugPrint("All Response Info: \(response)")
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM