Skip to content
Wes Bustraan edited this page Jan 5, 2025 · 1 revision

ASN1Codable

ASN1Codable is a Swift library for encoding and decoding ASN.1 data, designed to integrate seamlessly with Swift's Codable protocol.

What is ASN.1 and DER Encoding?

ASN.1 (Abstract Syntax Notation One) is a standard interface description language used to define data structures for representing, encoding, transmitting, and decoding data. It’s widely used in telecommunications, cryptography, and various file formats.

DER (Distinguished Encoding Rules) is a subset of ASN.1 encoding rules designed to produce unambiguous binary representations of data structures, ensuring compatibility across systems.

Installation

You can add ASN1Codable to your project using the Swift Package Manager (SPM).

  1. In Xcode, go to File > Add Packages....
  2. Enter the repository URL:
    https://github.com/w8wjb/ASN1Codable
    
  3. Choose a version or branch and add the package to your project.

Alternatively, update your Package.swift:

dependencies: [
    .package(url: "https://github.com/w8wjb/ASN1Codable", from: "1.0.0")
]

Getting Started

Basic Usage

Here’s an example of decoding an ASN.1-encoded sequence:

import ASN1Codable

struct Certificate: Codable {
    let version: Int
    let serialNumber: String
    let issuer: String
    let subject: String
}

let derData: Data = ... // ASN.1 DER-encoded data
do {
    let decoder = ASN1Decoder()
    let certificate = try decoder.decode(Certificate.self, from: derData)
    print("Issuer: \(certificate.issuer)")
} catch {
    print("Failed to decode: \(error)")
}

Encoding ASN.1 Data

import ASN1Codable

let certificate = Certificate(version: 2, serialNumber: "12345", issuer: "CA Inc.", subject: "John Doe")
do {
    let encoder = ASN1Encoder()
    let derData = try encoder.encode(certificate)
    print("Encoded DER data: \(derData)")
} catch {
    print("Failed to encode: \(error)")
}

Clone this wiki locally