IoT-Simulator/Sources/App/CustomCode/Utils/P256-keys-creation.swift
2024-12-11 17:31:26 +01:00

70 lines
2.2 KiB
Swift

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: UInt128) 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
let publicKey = key.publicKey.pemRepresentation
// UGLY: hardcoded
var httpRequest = URLRequest(url: URL(string: "http://publick-key-db.internal/key")!)
httpRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")
httpRequest.httpMethod = "POST"
let message: [String : Encodable] = [
"deviceID": deviceID,
"publicKey": publicKey
]
let data = try JSONSerialization.data(withJSONObject: message)
httpRequest.httpBody = data
let _ = try await URLSession.shared.upload(for: httpRequest, from: data)
return key
} catch {
// Do nothing
}
do {
let key = createPrivateP256Key()
try privateP256_2_pem(privateKey: key).write(to: URL(filePath: keyFilePath), atomically: true, encoding: String.Encoding.utf8)
return key
} catch {
throw ParsingError.ImpossibleToWriteKeyToFileSystem
}
}
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)
}