How can I get SecKeyRef from DER/PEM file

前端 未结 3 791
[愿得一人]
[愿得一人] 2020-11-29 20:05

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

3条回答
  •  执笔经年
    2020-11-29 20:46

    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!

    1. Received a certificate in the base64 encoded string sandwiched between header and tail like this (PEM format):

      -----BEGIN CERTIFICATE-----
      -----END CERTIFICATE-----
      
    2. 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)  
      }
      
    3. decode base64 string to NSData:

      let data = NSData(base64Encoded: cerStr, 
         options:NSData.Base64DecodingOptions.ignoreUnknownCharacters)!  
      
    4. Convert it from NSdata format to SecCertificate:

      let cert = SecCertificateCreateWithData(kCFAllocatorDefault, data)
      
    5. Now, this cert can be used to compare with the certificate received from the urlSession trust:

      certificateFromUrl = SecTrustGetCertificateAtIndex(...)
      if cert == certificate {
      }
      

提交回复
热议问题