Created
July 31, 2020 13:01
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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