Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com> Claude-Session: https://claude.ai/code/session_012bGzgsxrmbBhDzeMV2L57D
31 lines
1.3 KiB
Swift
31 lines
1.3 KiB
Swift
import Foundation
|
|
import Security
|
|
|
|
/// Passwords / API keys in the macOS login keychain.
|
|
enum Keychain {
|
|
static let service = "de.lichtkasten.app"
|
|
|
|
static func set(_ value: String, account: String) {
|
|
let base: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account]
|
|
SecItemDelete(base as CFDictionary)
|
|
guard !value.isEmpty else { return }
|
|
var add = base
|
|
add[kSecValueData as String] = Data(value.utf8)
|
|
add[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
|
|
SecItemAdd(add as CFDictionary, nil)
|
|
}
|
|
|
|
static func get(_ account: String) -> String? {
|
|
let q: [String: Any] = [kSecClass as String: kSecClassGenericPassword,
|
|
kSecAttrService as String: service,
|
|
kSecAttrAccount as String: account,
|
|
kSecReturnData as String: true,
|
|
kSecMatchLimit as String: kSecMatchLimitOne]
|
|
var out: AnyObject?
|
|
guard SecItemCopyMatching(q as CFDictionary, &out) == errSecSuccess, let d = out as? Data else { return nil }
|
|
return String(data: d, encoding: .utf8)
|
|
}
|
|
}
|