Files
lichtkasten/Sources/Lichtkasten/Services/Keychain.swift
T

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)
}
}