8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Parse X509 certificate in Swift 2.0

Last updated at Posted at 2015-11-17

Parse X509 certificate in Swift 2.0

X509の証明書をSwiftでパースしました.

事前準備

  • DERフォーマットの証明書を用意しておく
  • {Project Name}/Resources/mykey.der として保存しておく

Parse.swift

X509Parser.swift
import Foundation
import Security

class X509Parser {
    func parse() {
    	// converting der file to secCertificate type
        let secCertificate: SecCertificate = getSecCertificate()
        // converting SecCertificate to SecTrust
        let secTrust: SecTrust? = getSecTrust(secCertificate)
        
        // Sample: extracting public key
        let publicKey: SecKey? = SecTrustCopyPublicKey(secTrust!)
        print(publicKey)
    }

    func getSecCertificate() -> SecCertificate {
        let path: String = NSBundle.mainBundle().pathForResource("mykey", ofType: "der")!
        let key: NSData = NSData(contentsOfFile: path)!
        let secCertificate: SecCertificate = SecCertificateCreateWithData(kCFAllocatorDefault, key)!
        return secCertificate
    }

    func getSecTrust(secCertificate: SecCertificate) -> SecTrust? {
        var secTrust: SecTrust?
        SecTrustCreateWithCertificates(secCertificate, SecPolicyCreateBasicX509(), &secTrust)
        return secTrust
    }
}

使い方

プロジェクトをシングルページアプリケーションを選択して作成後,事前準備を行い,コードをコピペすれば動くと思います.
行数書いてないのにSwiftのコードを書くの疲れる...

公開鍵以外の情報について

Apple > Security Framework Reference > Certificate, Key, and Trust Services Reference

8
6
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
8
6

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?