Skip to content

Instantly share code, notes, and snippets.

@joncardasis
Created March 21, 2018 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save joncardasis/8c626d321a88769b9780188d7f79559d to your computer and use it in GitHub Desktop.
Save joncardasis/8c626d321a88769b9780188d7f79559d to your computer and use it in GitHub Desktop.
Example of direct OpenSSL usage in Swift
//
// ssltest.swift
//
// Created by Cardasis, Jon C. (CAC) on 1/22/18.
// Copyright © 2018 Jon Cardasis. All rights reserved.
//
import OpenSSL
import Security
/// Create typealias' for macros not imported to Swift
fileprivate typealias X509 = OpaquePointer
public class X509Certificate {
public static func issuerName(for certificate: SecCertificate) -> String? {
let data = SecCertificateCopyData(certificate) as NSData
var firstByte: UnsafePointer? = data.bytes.assumingMemoryBound(to: UInt8.self)
let certificateX509: X509? = d2i_X509(nil, &firstByte, data.length)
let issuer = issuerName(for: certificateX509)
X509_free(certificateX509)
return issuer
}
//MARK: - Private
private static func issuerName(for x509Certificate: X509?) -> String? {
var issuer: String?
guard let x509Certificate = x509Certificate else {
return nil
}
let issuerName = X509_get_issuer_name(x509Certificate)
let nid = NID_commonName
let index = X509_NAME_get_index_by_NID(issuerName, nid, -1)
if let issuerNameEntry /*X509_NAME_ENTRY*/ = X509_NAME_get_entry(issuerName, index) {
if let issuerNameASN1 = X509_NAME_ENTRY_get_data(issuerNameEntry),
let issuerNameUTF8 = ASN1_STRING_get0_data(issuerNameASN1) { // string rep of DES ASN1 structure
issuer = String(cString: issuerNameUTF8)
}
}
return issuer
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment