问题
I am using below code for SSL pinning in Kotlin Multiplatform using Ktor.
I am having crash at this line of code
val remoteCertificateData : NSData = SecCertificateCopyData(certificate) as NSData
Here is the function.
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)
}
}
回答1:
After so many research I manage to convert iOS code in Kotlin Multiplatform for 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)
}
}
来源:https://stackoverflow.com/questions/58777854/ktor-multiplatform-ssl-pinning-for-ios-in-kotlin