/
KeychainHelper.swift
74 lines (62 loc) · 2.34 KB
/
KeychainHelper.swift
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
//
// KeychainHelper.swift
// keychainDemo
//
// Created by Anshumaan Singh on 24/11/22.
//
import Foundation
import Security
import UIKit
class KeychainHelper {
private static let teamID = AppConstants.teamID
private static let accessGroup = "\(teamID).app.crosspass.ios.keychain_access_group"
class func save(key: String, data: Data) -> OSStatus {
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccount as String : key,
kSecValueData as String : data,
//kSecAttrAccessible as String : kSecAttrAccessibleAlwaysThisDeviceOnly
kSecAttrAccessible as String : kSecAttrAccessibleAfterFirstUnlockThisDeviceOnly,
kSecAttrAccessGroup as String : accessGroup
] as [String : Any]
SecItemDelete(query as CFDictionary)
return SecItemAdd(query as CFDictionary, nil)
}
class func load(key: String) -> Data? {
let query = [
kSecClass as String : kSecClassGenericPassword,
kSecAttrAccount as String : key,
kSecReturnData as String : kCFBooleanTrue!,
kSecAttrAccessGroup as String : accessGroup,
kSecMatchLimit as String : kSecMatchLimitOne ] as [String : Any]
var dataTypeRef: AnyObject? = nil
let status: OSStatus = SecItemCopyMatching(query as CFDictionary, &dataTypeRef)
if status == noErr {
return dataTypeRef as! Data?
} else {
return nil
}
}
class func deleteKey(key:String)-> OSStatus{
let query = [
kSecClass as String : kSecClassGenericPassword as String,
kSecAttrAccessGroup as String : accessGroup,
kSecAttrAccount as String : key] as [String : Any]
return SecItemDelete(query as CFDictionary)
}
class func createUniqueID() -> String {
let uuid: CFUUID = CFUUIDCreate(nil)
let cfStr: CFString = CFUUIDCreateString(nil, uuid)
let swiftString: String = cfStr as String
return swiftString
}
}
extension Data {
init<T>(from value: T) {
var value = value
self.init(buffer: UnsafeBufferPointer(start: &value, count: 1))
}
func to<T>(type: T.Type) -> T {
return self.withUnsafeBytes { $0.load(as: T.self) }
}
}