Skip to content

Instantly share code, notes, and snippets.

@davidmtamas
Created April 2, 2020 07:16
Show Gist options
  • Save davidmtamas/d571c0173fe66376c69884c7a7ad7cfd to your computer and use it in GitHub Desktop.
Save davidmtamas/d571c0173fe66376c69884c7a7ad7cfd to your computer and use it in GitHub Desktop.

Revisions

  1. davidmtamas created this gist Apr 2, 2020.
    27 changes: 27 additions & 0 deletions CryptoKitExample.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,27 @@
    import CryptoSwift
    import CommonCrypto

    #if canImport(CryptoKit)
    import CryptoKit
    #endif

    public final class PublicKeyPinner {
    ...
    /// Creates a hash from the received data using the `sha256` algorithm.
    /// `Returns` the `base64` encoded representation of the hash.
    ///
    /// To replicate the output of the `openssl dgst -sha256` command, an array of specific bytes need to be appended to
    /// the beginning of the data to be hashed.
    /// - Parameter data: The data to be hashed.
    private func hash(data: Data) -> String {
    // Add the missing ASN1 header for public keys to re-create the subject public key info
    var keyWithHeader = Data(rsa2048Asn1Header)
    keyWithHeader.append(data)
    // Check if iOS 13 is available, and use CryptoKit's hasher
    if #available(iOS 13, *) {
    return Data(SHA256.hash(data: keyWithHeader)).base64EncodedString()
    } else {
    ...
    }
    }
    }