美文网首页
Swift 加载本地证书并提取公钥

Swift 加载本地证书并提取公钥

作者: CYC666 | 来源:发表于2023-03-16 11:37 被阅读0次
    
    // 使用证书文件路径加载证书
            let certificateFilePath = Bundle.main.path(forResource: "cert", ofType: "cer")!
            let certificateData = try! Data(contentsOf: URL(fileURLWithPath: certificateFilePath))
            let certificate = SecCertificateCreateWithData(nil, certificateData as CFData)
    
            // 提取证书公钥
            if let publicKey = extractPublicKey(from: certificate!) {
                // 公钥提取成功,可以使用
                print("提取公钥成功")
                print(publicKey)
                
            } else {
                // 公钥提取失败,处理错误
                print("提取公钥失败")
            }
    
    =====================
    // 导出公钥
        func extractPublicKey(from certificate: SecCertificate) -> SecKey? {
            var key: SecKey?
            let policy = SecPolicyCreateBasicX509()
            var trust: SecTrust?
            let status = SecTrustCreateWithCertificates(certificate, policy, &trust)
            guard status == errSecSuccess, let serverTrust = trust else {
                return nil
            }
            let serverPublicKey = SecTrustCopyPublicKey(serverTrust)
            if let publicKey = serverPublicKey {
                key = publicKey
            }
            return key
        }
    

    相关文章

      网友评论

          本文标题:Swift 加载本地证书并提取公钥

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