punchnet-macos/punchnet/Core/KeychainStore.swift
2026-01-19 17:36:46 +08:00

78 lines
2.0 KiB
Swift
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//
// KeychainStore.swift
// punchnet
//
// Created by on 2026/1/19.
//
import Foundation
import Security
enum KeychainError: Error {
case unexpectedStatus(OSStatus)
}
final class KeychainStore {
public static var shared: KeychainStore = .init(service: Bundle.main.bundleIdentifier!)
private let service: String
private init(service: String) {
self.service = service
}
func save(_ data: Data, account: String) throws {
let query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: service,
kSecAttrAccount: account,
kSecValueData: data
]
//
SecItemDelete(query as CFDictionary)
let status = SecItemAdd(query as CFDictionary, nil)
guard status == errSecSuccess else {
throw KeychainError.unexpectedStatus(status)
}
}
func load(account: String) throws -> Data? {
let query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: service,
kSecAttrAccount: account,
kSecReturnData: true,
kSecMatchLimit: kSecMatchLimitOne
]
var result: AnyObject?
let status = SecItemCopyMatching(query as CFDictionary, &result)
if status == errSecItemNotFound {
return nil
}
guard status == errSecSuccess else {
throw KeychainError.unexpectedStatus(status)
}
return result as? Data
}
func delete(account: String) throws {
let query: [CFString: Any] = [
kSecClass: kSecClassGenericPassword,
kSecAttrService: service,
kSecAttrAccount: account
]
let status = SecItemDelete(query as CFDictionary)
guard status == errSecSuccess || status == errSecItemNotFound else {
throw KeychainError.unexpectedStatus(status)
}
}
}