我正在使用下面的代码通过Ktor在Kotlin Multiplatform中进行SSL固定。
我在此行代码上崩溃
val remoteCertificateData : NSData = SecCertificateCopyData(certificate) as NSData
这是功能。
override fun URLSession(
session: NSURLSession,
didReceiveChallenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Unit
) {
val serverTrust = didReceiveChallenge.protectionSpace.serverTrust
val certificate = SecTrustGetCertificateAtIndex(serverTrust,0)
var result: SecTrustResultType = 0u
memScoped{
val nativeResult = alloc<SecTrustResultTypeVar>()
nativeResult.value = result
SecTrustEvaluate(serverTrust!!, nativeResult.ptr)
}
val remoteCertificateData : NSData = SecCertificateCopyData(certificate) as NSData
val bundle = NSBundle.bundleForClass(objc_getRequiredClass("IosClientEngine"))
val pathToCert = bundle.pathForResource("MyCertificate","cer")
val localCertificate : NSData = NSData.dataWithContentsOfFile(pathToCert!!)!!
if (localCertificate == remoteCertificateData) {
completionHandler(NSURLSessionAuthChallengeUseCredential,NSURLCredential.create(serverTrust))
} else {
completionHandler(NSURLSessionAuthChallengeUseCredential, null)
}
}
答案 0 :(得分:0)
经过大量研究,我设法在Kotlin Multiplatform for iOS中转换iOS代码。
override fun URLSession(
session: NSURLSession,
didReceiveChallenge: NSURLAuthenticationChallenge,
completionHandler: (NSURLSessionAuthChallengeDisposition, NSURLCredential?) -> Unit
) {
val serverTrust = didReceiveChallenge.protectionSpace.serverTrust
var result: SecTrustResultType = 0u
memScoped{
val nativeResult = alloc<SecTrustResultTypeVar>()
nativeResult.value = result
SecTrustEvaluate(serverTrust!!, nativeResult.ptr)
}
val serverCertificate = SecTrustGetCertificateAtIndex(serverTrust,0)
val serverCertificateData = SecCertificateCopyData(serverCertificate)
val data = CFDataGetBytePtr(serverCertificateData)
val size = CFDataGetLength(serverCertificateData)
val cert1 = NSData.dataWithBytes(data,size.toULong())
val pathToCert = NSBundle.mainBundle.pathForResource("Your Certificate","cer")
val localCertificate : NSData = NSData.dataWithContentsOfFile(pathToCert!!)!!
if (localCertificate == cert1) {
completionHandler(NSURLSessionAuthChallengeUseCredential,NSURLCredential.create(serverTrust))
} else {
completionHandler(NSURLSessionAuthChallengeCancelAuthenticationChallenge, null)
}
}