I need to integrate my iPhone app with a system, and they require to encrypt data by a given public key, there are 3 files in 3 different format .xml .der and .pem, I have r
After hours of effort researching online with the help of this post, I finally get it working perfectly. Here is the notes with working Swift code of the most current version. I hope it can help someone!
Received a certificate in the base64 encoded string sandwiched between header and tail like this (PEM format):
-----BEGIN CERTIFICATE-----
-----END CERTIFICATE-----
strip out the header and the tail, such as
// remove the header string
let offset = ("-----BEGIN CERTIFICATE-----").characters.count
let index = certStr.index(cerStr.startIndex, offsetBy: offset+1)
cerStr = cerStr.substring(from: index)
// remove the tail string
let tailWord = "-----END CERTIFICATE-----"
if let lowerBound = cerStr.range(of: tailWord)?.lowerBound {
cerStr = cerStr.substring(to: lowerBound)
}
decode base64 string to NSData:
let data = NSData(base64Encoded: cerStr,
options:NSData.Base64DecodingOptions.ignoreUnknownCharacters)!
Convert it from NSdata format to SecCertificate:
let cert = SecCertificateCreateWithData(kCFAllocatorDefault, data)
Now, this cert can be used to compare with the certificate received from the urlSession trust:
certificateFromUrl = SecTrustGetCertificateAtIndex(...)
if cert == certificate {
}