gpt4 book ai didi

ios - 以编程方式创建 URLAuthenticationChallenge 时如何获得非零 serverTrust 值?

转载 作者:IT王子 更新时间:2023-10-29 05:44:58 27 4
gpt4 key购买 nike

我的 Swift iOS 应用程序中有公钥固定代码,效果很好。

我现在正在构建单元测试,该单元测试将在不需要网络连接/实时服务器的情况下测试公钥固定代码。我几乎可以正常工作了,但是我不知道如何以编程方式创建具有非零 serverTrust 的 URLAuthenticationChallenge?所有 Apple 文档都指出,如果您的身份验证方法是 NSURLAuthenticationMethodServerTrust,则这应该是非零。在下面的示例中,我使用本地计算机生成的 p12 和 cer 文件来构建 URLCredential。无论我做什么,challenge.protectionSpace.serverTrust 总是返回 nil。

let protectionSpace = URLProtectionSpace(host: "mockSession",
port: 0,
protocol: "https",
realm: nil,
authenticationMethod: NSURLAuthenticationMethodServerTrust)

var urlCredential:URLCredential?
if let p12Data = try? Data(contentsOf: URL(fileURLWithPath: Bundle.init(for: type(of: self)).path(forResource: "cm7justindomnit", ofType: "p12") ?? "")),
let cerData = try? Data(contentsOf: URL(fileURLWithPath: Bundle.init(for: type(of: self)).path(forResource: "cm7justindomnit", ofType: "cer") ?? "")){
let options: NSDictionary = [kSecImportExportPassphrase:"password"]
var items: CFArray?
let _ = SecPKCS12Import(p12Data as CFData, options, &items)
if let items = items {
let objectsData = Data.init(from: CFArrayGetValueAtIndex(items, 0))
let objects = objectsData.toArray(type: CFDictionary.self).first
let secIdentityData = Data.init(from: CFDictionaryGetValue(objects, Unmanaged.passUnretained(kSecImportItemIdentity).toOpaque()))
if let secIdentity = secIdentityData.toArray(type: SecIdentity.self).first {
if let secCertifiate = SecCertificateCreateWithData(kCFAllocatorDefault, cerData as CFData) {
urlCredential = URLCredential(identity: secIdentity, certificates: [secCertifiate], persistence: .forSession)
}
}
}
}

let challenge = URLAuthenticationChallenge(protectionSpace: protectionSpace,
proposedCredential: urlCredential,
previousFailureCount: 0,
failureResponse: nil,
error: nil,
sender: self)

我有一个数据扩展来处理 UnsafeBufferPointers。

extension Data {

init<T>(from value: T) {
var value = value
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}

func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.pointee }
}

func toArray<T>(type: T.Type) -> [T] {
return self.withUnsafeBytes {
[T](UnsafeBufferPointer(start: $0, count: self.count/MemoryLayout<T>.stride))
}
}
}

最佳答案

我意识到这是一个较旧的问题,但今天我在为我的 SSL 固定代码编写测试时遇到了同样的问题。我通过子类化 URLProtectionSpace

解决了它
private class TestURLProtectionSpace: URLProtectionSpace {
var internalServerTrust: SecTrust?
override var serverTrust: SecTrust? {
return internalServerTrust
}
}

let protectionSpace = TestURLProtectionSpace(
host: "myhost.com",
port: 443,
protocol: "https",
realm: nil,
authenticationMethod: NSURLAuthenticationMethodServerTrust
)
protectionSpace.internalServerTrust = serverTrust

关于ios - 以编程方式创建 URLAuthenticationChallenge 时如何获得非零 serverTrust 值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45066343/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com