import Foundation import FoundationNetworking import Crypto public func createPrivateP256Key() -> P256.Signing.PrivateKey { return P256.Signing.PrivateKey() } public func createPublickP256Key(privateKey: P256.Signing.PrivateKey ) -> P256.Signing.PublicKey { return privateKey.publicKey } public func publicP256_2_Spki(publicKey: P256.Signing.PublicKey) -> String { return publicKey.pemRepresentation } public func privateP256_2_pem(privateKey: P256.Signing.PrivateKey) -> String { return privateKey.pemRepresentation } // UGLY: Refactor to make it easier to comprehend public func fetchPrivateP256Key(deviceID: UInt) async throws -> P256.Signing.PrivateKey { // UGLY: but fast let privateKeyFolder = ProcessInfo.processInfo.environment["PRIVATE_KEY_FOLDER"] ?? "./Private/PrivateKeysP256" let keyFilePath = "\(privateKeyFolder)/\(deviceID)-Kr.pem" do { let key = try pem2_P265_PrivateKey(filePath: keyFilePath) // TODO: send public key to another server return key } catch { // Do nothing } let key = createPrivateP256Key() let publicKey = key.publicKey.pemRepresentation try privateP256_2_pem(privateKey: key).write(to: URL(filePath: keyFilePath), atomically: true, encoding: String.Encoding.utf8) // UGLY: hardcoded var httpRequest = URLRequest(url: URL(string: "http://public-key-db.internal/key")!) httpRequest.setValue("application/json", forHTTPHeaderField: "Content-Type") httpRequest.httpMethod = "POST" let message = PublicKeyMessage(deviceID: deviceID, publicKey: publicKey) let encoder = JSONEncoder() let data = try encoder.encode(message) httpRequest.httpBody = data let _ = try await URLSession.shared.upload(for: httpRequest, from: data) return key } private func pem2_P265_PrivateKey(filePath: String) throws -> P256.Signing.PrivateKey { let pemEncodedKey = try String(contentsOf: URL(filePath: filePath), encoding: .utf8) return try P256.Signing.PrivateKey(pemRepresentation: pemEncodedKey) }