Skip to content

Instantly share code, notes, and snippets.

@davidmtamas
Created April 2, 2020 07:16
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 davidmtamas/d571c0173fe66376c69884c7a7ad7cfd to your computer and use it in GitHub Desktop.
Save davidmtamas/d571c0173fe66376c69884c7a7ad7cfd to your computer and use it in GitHub Desktop.
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 {
...
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment