美文网首页
swift实现https客户端认证(mac app)

swift实现https客户端认证(mac app)

作者: w_j_y | 来源:发表于2020-10-12 10:50 被阅读0次

使用私钥和证书进行https客户端认证

网上给的一些客户端认证的方法,在mac app上效果不太好,例如需要生成p12证书、使用时会弹出授权使用私钥的系统提示。
研究了下苹果的官方文档,以下是完美的解决方案

私钥和证书加载类

import Cocoa
class IdentityUtil{
    
    private static var identity: IdentityAndTrust?
    
    public static func loadIdentity() -> IdentityAndTrust{
        
        if(identity != nil){
            return identity!
        }else{
            identity = extractIdentity()
            return identity!
        }
        
    }
    
    //获取客户端证书相关信息
    static func  extractIdentity() -> IdentityAndTrust{
        loadKey()
        return loadPem()
    }
    //加载证书
    static func loadPem()-> IdentityAndTrust{
        
        let pem =
        "MIIC/jCCAeagA... 你的客户端证书(需去除首位的-----BEGIN CERTIFICATE-----和-----END CERTIFICATE------,以及去除换行)...cuY2cg="
        
        let certData = Data(base64Encoded: pem)!
        let certificate: SecCertificate = SecCertificateCreateWithData(nil,certData as CFData)!
        
        var identity: SecIdentity?
        SecIdentityCreateWithCertificate(nil, certificate, &identity)
        
        let certArray = [ certificate ]
        
        var trust: SecTrust?
        SecTrustCreateWithCertificates(certArray as AnyObject,SecPolicyCreateBasicX509(),&trust)
        return IdentityAndTrust(identityRef: identity!,trust:trust!,certArray:  certArray)
        
    }
    //加载私钥
    static func loadKey(){
        let keyBase64 = "MIIEowIBAAKCAQ...你的私钥(需要去除首尾的-----BEGIN PRIVATE KEY-----和-----END PRIVATE KEY-----,以及去除换行) ...MnMOc+wl"
        let keyData = Data(base64Encoded: keyBase64)!
        let tag = "com.wjy.mykey".data(using: .utf8)!
        
        let key = SecKeyCreateWithData(keyData as NSData, [
            kSecAttrKeyType: kSecAttrKeyTypeRSA,
            kSecAttrApplicationTag as String: tag,
            kSecAttrKeyClass: kSecAttrKeyClassPrivate,
            ] as NSDictionary, nil)!
        let addquery: [String: Any] = [kSecClass as String: kSecClassKey,
                                       kSecAttrApplicationTag as String: tag,
                                       kSecAttrKeyType as String:kSecAttrKeyTypeRSA,
                                       kSecValueRef as String: key]
        
        SecItemAdd(addquery as CFDictionary, nil)
        // SecItemDelete(addquery as CFDictionary)
    }
    
    
}

//认证数据结构体
struct IdentityAndTrust {
    var identityRef:SecIdentity
    var trust:SecTrust
    var certArray:[SecCertificate]
}

URLSession代理类

import Cocoa

class ClientCertificateDelegate: NSObject, NSApplicationDelegate,URLSessionDelegate {
    
    var identity: IdentityAndTrust!
    
    func urlSession(_ session: URLSession, didReceive challenge: URLAuthenticationChallenge,
                    completionHandler: @escaping (URLSession.AuthChallengeDisposition,
        URLCredential?) -> Void) {
        //认证服务器(这里不使用服务器证书认证,只需地址是我们定义的几个地址即可信任)
        if challenge.protectionSpace.authenticationMethod
            == NSURLAuthenticationMethodServerTrust {
            print("服务器认证!")
            let credential = URLCredential(trust: challenge.protectionSpace.serverTrust!)
            completionHandler(.useCredential, credential)
        }else if challenge.protectionSpace.authenticationMethod
            == NSURLAuthenticationMethodClientCertificate {
            print("客户端证书认证!")
            //获取客户端证书相关信息
            if self.identity == nil{
                self.identity = IdentityUtil.loadIdentity()
            }
            let urlCredential:URLCredential = URLCredential(
                identity: self.identity.identityRef,
                certificates: nil,
                persistence: .none)
            completionHandler(.useCredential, urlCredential)
        }
    }
    
}

调用接口demo


func getData(){
        //1、创建URL
        let url: URL = URL(string: "https://xxxx")!
        
        //2、创建URLRequest
        let request: URLRequest = URLRequest(url: url)
        
        //3、创建URLSession
        let configration = URLSessionConfiguration.default
        let session =  URLSession(configuration: configration,delegate: ClientCertificateDelegate(), delegateQueue:OperationQueue.main)
        
        //4、URLSessionTask子类
        let task: URLSessionDataTask = session.dataTask(with: request) { (data, response, error) in
            if error == nil {
                DispatchQueue.main.async {
                    if let data = data {
                        //得到数据,回到主线程
                            DispatchQueue.main.async {
                                //更新界面
                               
                            }
                            //完成
                            return
                    }
                    
                }
            }
        }
        
        //5、启动任务
        task.resume()
        
    }

相关文章

  • swift实现https客户端认证(mac app)

    使用私钥和证书进行https客户端认证 网上给的一些客户端认证的方法,在mac app上效果不太好,例如需要生成p...

  • NGINX单双向混合认证

    本文介绍通过NGINX配置实现WEB服务器单双向混合认证: 实现HTTPS服务器证书认证 对于一般网络客户端,强制...

  • Swift5.0 实现HTTPS双向认证

    网络请求库使用Alamofire 使用 参考资料:https://leenarts.net/2020/02/28/...

  • HTTPSS证书制作笔记

    参考资料 Android HTTPS 自制证书实现双向认证 制作证书 使用证书 客户端使用 需要truststor...

  • iOS_HTTPS认证

    HTTPS认证 单向认证:指客户端验证服务端的身份,服务端不验证客户端身份双向认证:指客户端验证服务端身份,服务端...

  • oc转swift

    网站 https://objectivec2swift.com 客户端 https://iswift.org

  • 【Go Web开发】认证请求

    上一篇文章[https://www.jianshu.com/p/3dbc58430d7a]实现了客户端通过发送认证...

  • swift5实现购物app

    swift5实现购物app

  • 网络安全(III) 之 HTTPS安全

    HTTPS 认证流程https 认证流程 1. 客户端发起HTTPS请求这个没什么好说的,就是用户在浏览器里输入一...

  • Swift

    Swift 是2014年apple 官方推出的编程语言,支持编写iOS App,Mac App等苹果全平台App,...

网友评论

      本文标题:swift实现https客户端认证(mac app)

      本文链接:https://www.haomeiwen.com/subject/grdupktx.html