ASN1 DER Decoder for X.509 Certificate
- iOS 9.0+ | macOS 10.10+
- Xcode 9
You can use CocoaPods to install ASN1Decoder by adding it to your Podfile:
platform:ios,'9.0'use_frameworks!target'MyApp'dopod'ASN1Decoder'endYou can use Carthage to install ASN1Decoder by adding it to your Cartfile:
github "filom/ASN1Decoder"
import ASN1Decoder
do{letx509=tryX509Certificate(data: certData)letsubject= x509.subjectDistinguishedName ??""}catch{print(error)}Define a delegate for URLSession
import Security
import ASN1Decoder
classPinningURLSessionDelegate:NSObject,URLSessionDelegate{varpublicKeyHexEncoded:String!publicinit(publicKeyHexEncoded:String){self.publicKeyHexEncoded = publicKeyHexEncoded.uppercased()}func urlSession(_ session:URLSession, didReceive challenge:URLAuthenticationChallenge, completionHandler:@escaping(URLSession.AuthChallengeDisposition,URLCredential?)->Swift.Void){if(challenge.protectionSpace.authenticationMethod == NSURLAuthenticationMethodServerTrust){iflet serverTrust = challenge.protectionSpace.serverTrust {varsecresult=SecTrustResultType.invalid
letstatus=SecTrustEvaluate(serverTrust,&secresult)if status == errSecSuccess {iflet serverCertificate =SecTrustGetCertificateAtIndex(serverTrust,0){letserverCertificateCFData=SecCertificateCopyData(serverCertificate)letdata=CFDataGetBytePtr(serverCertificateCFData)letsize=CFDataGetLength(serverCertificateCFData)letcertData=NSData(bytes: data, length: size)do{letx509cert=tryX509Certificate(data: certData asData)iflet pk = x509cert.publicKey?.key {letserverPkHexEncoded=dataToHexString(pk)if publicKeyHexEncoded == serverPkHexEncoded {completionHandler(.useCredential,URLCredential(trust:serverTrust))return}}}catch{print(error)}}}}}completionHandler(.cancelAuthenticationChallenge,nil)}func dataToHexString(_ data:Data)->String{return data.map{String(format:"%02X", $0)}.joined()}}Then create a URLSession and use it as usual
letpublicKeyHexEncoded="..." // your HTTPS certifcate public key
letsession=URLSession(
configuration:URLSessionConfiguration.ephemeral,
delegate:PinningURLSessionDelegate(publicKeyHexEncoded: publicKeyHexEncoded),
delegateQueue:nil)To extract the public key from your certificate with openssl use this command line
openssl x509 -modulus -noout < certificate.cer
import ASN1Decoder
iflet appStoreReceiptURL =Bundle.main.appStoreReceiptURL,FileManager.default.fileExists(atPath: appStoreReceiptURL.path){do{letreceiptData=tryData(contentsOf: appStoreReceiptURL, options:.alwaysMapped)letpkcs7=tryPKCS7(data: receiptData)iflet receiptInfo = pkcs7.receipt(){print(receiptInfo.originalApplicationVersion)}}catch{print(error)}}