Skip to content

Instantly share code, notes, and snippets.

@alfavata
Created July 31, 2020 13:01
Show Gist options
  • Save alfavata/06b7517d0eb0fbf454a6102f36caf61b to your computer and use it in GitHub Desktop.
Save alfavata/06b7517d0eb0fbf454a6102f36caf61b to your computer and use it in GitHub Desktop.
func encrypt(_ text: String) -> String? {
guard
let bundle = Bundle(identifier: "com.example.bundle.identifier"),
let url = bundle.url(forResource: "certificate", withExtension: "der"),
let certData = try? Data(contentsOf: url),
let cert = SecCertificateCreateWithData(nil, certData as CFData) else {
print("Couldn't find/create pinned certificate")
return nil
}
var trust: SecTrust?
guard SecTrustCreateWithCertificates([cert] as CFTypeRef, SecPolicyCreateBasicX509(), &trust) == errSecSuccess, trust != nil else {
print("Couldn't create trust with pinned certificate")
return nil
}
guard let key = SecTrustCopyPublicKey(trust!) else {
print("Couldn't extract public key from certificate")
return nil
}
let algorithm = SecKeyAlgorithm.rsaEncryptionOAEPSHA256AESGCM
guard SecKeyIsAlgorithmSupported(key, .encrypt, algorithm) else {
print("Algorithm \(algorithm.rawValue) not supported by key")
return nil
}
guard let plainData = text.data(using: .utf8) else {
print("Cannot convert plain text to UTF8-encoded data")
return nil
}
var error: Unmanaged<CFError>?
guard let encryptedData = SecKeyCreateEncryptedData(key, algorithm, plainData as CFData, &error) else {
print("Encryption failed. Error: " + (error?.takeRetainedValue().localizedDescription ?? "unknown"))
return nil
}
return String(data: encryptedData as Data, encoding: .utf8)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment