SecureStorageSample/SecureStorageSample/Services/ExternalKeyMaterialProvider.swift
Matt Bruce f4a4f1a527 comments
Signed-off-by: Matt Bruce <mbrucedogs@gmail.com>
2026-01-17 12:18:05 -06:00

31 lines
1.1 KiB
Swift

import CryptoKit
import Foundation
import LocalData
/// Supplies external key material for the encrypted storage demo.
/// The provider persists the generated key material so encryption remains stable across launches.
nonisolated
struct ExternalKeyMaterialProvider: KeyMaterialProviding {
private enum Constants {
static let keyLength = 32
}
/// Returns a stable 256-bit key, generating and persisting it on first use.
func keyMaterial(for keyName: String) async throws -> Data {
let key = StorageKey.externalKeyMaterial
if let existing = try? await StorageRouter.shared.get(key) {
return existing
}
// CryptoKit ensures the material is cryptographically random.
let symmetricKey = SymmetricKey(size: .bits256)
let material = symmetricKey.withUnsafeBytes { Data($0) }
guard material.count == Constants.keyLength else {
throw StorageError.securityApplicationFailed
}
try await StorageRouter.shared.set(material, for: key)
return material
}
}