31 lines
1.1 KiB
Swift
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
|
|
}
|
|
}
|