// 使用证书文件路径加载证书
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
}
网友评论