Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you import a DER certificate in swift?

Tags:

macos

swift

So it seems as though a bunch of methods have changed which have broken things in my current codebase. I'm currently getting the following error:

Cannot convert the expression's type '(CFAllocator!, data: @lvalue NSData)' to type 'CFData!'

Here's the relevant code:

let mainbun = NSBundle.pathForResource("mainkey", ofType: "der", inDirectory: "/myapppath")
var key: NSData = NSData(base64EncodedString: mainbun!, options: nil)!
var turntocert: SecCertificateRef = SecCertificateCreateWithData(kCFAllocatorDefault, data: key)

I have it working with a bridging header but i would still like to just be able to create the certificate reference directly in swift.


UPDATE: this works

var bundle: NSBundle = NSBundle.mainBundle()
var mainbun = bundle.pathForResource("keyfile", ofType: "der")
var key: NSData = NSData(contentsOfFile: mainbun!)!
var turntocert: SecCertificateRef =
SecCertificateCreateWithData(kCFAllocatorDefault, key).takeRetainedValue()
like image 935
nsij22 Avatar asked Sep 29 '22 05:09

nsij22


1 Answers

In Swift, SecCertificateCreateWithData returns an Unmanaged type. You need to get the value of the unmanaged reference with takeRetainedValue().

let mainbun = NSBundle.pathForResource("mainkey", ofType: "der", inDirectory: "/myapppath")
var key: NSData = NSData(base64EncodedString: mainbun!, options: nil)!
var turntocert: SecCertificateRef = 
    SecCertificateCreateWithData(kCFAllocatorDefault, key).takeRetainedValue()

The core problem you have is converting CFData to NSData. See this question

like image 86
bbarnhart Avatar answered Oct 03 '22 03:10

bbarnhart