MasterKeyUtil.swift 5.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175
  1. //
  2. // SecureStorage.swift
  3. // Pods
  4. //
  5. // Created by Qindi on 02/12/24.
  6. //
  7. import CryptoKit
  8. import LocalAuthentication
  9. public class MasterKeyUtil {
  10. static let shared = MasterKeyUtil()
  11. private let keyAlias = "_iosx_security_master_key"
  12. private let prefsKeyAlias = "_iosx_security_master_key_easysoft_"
  13. private let serverKeyAlias = "_iosx_security_master_key_server_"
  14. private init() {}
  15. func base64toData(_ base64: String) -> Data? {
  16. guard let data = Data(base64Encoded: base64) else {
  17. return nil
  18. }
  19. return data
  20. }
  21. func generateAndStoreKey(_ alias: String, key_s: String? = nil) throws {
  22. if try isKeyExists(keyAliasCode: alias) {
  23. // print("Master Key already exists, skipping generation.")
  24. return
  25. }
  26. let key = (key_s != nil) ? nil : SymmetricKey(size: .bits256)
  27. guard let keyData = key?.withUnsafeBytes({ Data($0) }) ?? base64toData(key_s!) else {
  28. return
  29. }
  30. let query: [String: Any] = [
  31. kSecClass as String: kSecClassKey,
  32. kSecAttrApplicationTag as String: alias,
  33. kSecValueData as String: keyData,
  34. kSecAttrAccessible as String: kSecAttrAccessibleAfterFirstUnlock
  35. ]
  36. SecItemDelete(query as CFDictionary) // Remove if it exists
  37. let status = SecItemAdd(query as CFDictionary, nil)
  38. guard status == errSecSuccess else {
  39. throw NSError(domain: "KeychainError", code: Int(status), userInfo: nil)
  40. }
  41. }
  42. func generateAndStorePrefsKey() throws {
  43. try generateAndStoreKey(prefsKeyAlias)
  44. }
  45. func generateAndStoreMasterKey() throws {
  46. try generateAndStoreKey(keyAlias)
  47. }
  48. func isDeviceNotSecure() -> Bool {
  49. let context = LAContext()
  50. var error: NSError?
  51. if !context.canEvaluatePolicy(.deviceOwnerAuthentication, error: &error) || Utils.shouldRequestAuthentication() {
  52. return true
  53. } else {
  54. return false
  55. }
  56. }
  57. func isKeyExists(keyAliasCode: String) throws -> Bool {
  58. let query: [String: Any] = [
  59. kSecClass as String: kSecClassKey,
  60. kSecAttrApplicationTag as String: keyAliasCode,
  61. kSecReturnData as String: false // We only check existence, not retrieve data
  62. ]
  63. let status = SecItemCopyMatching(query as CFDictionary, nil)
  64. if status == errSecItemNotFound {
  65. return false
  66. } else if status == errSecSuccess {
  67. return true
  68. } else {
  69. throw NSError(domain: "KeychainError", code: Int(status), userInfo: nil)
  70. }
  71. }
  72. func getMasterKey() throws -> SymmetricKey {
  73. if Nexilis.checkingAccess(key: "authentication") && isDeviceNotSecure() && Nexilis.dispatch == nil {
  74. var result = false
  75. Nexilis.dispatch = DispatchGroup()
  76. Nexilis.dispatch?.enter()
  77. Utils.authenticateWithBiometrics { success, errorMessage in
  78. if success {
  79. print("Access granted!")
  80. result = true
  81. } else {
  82. print("Access denied: \(errorMessage ?? "Unknown error")")
  83. }
  84. if let dispatch = Nexilis.dispatch {
  85. dispatch.leave()
  86. }
  87. }
  88. Nexilis.dispatch?.wait()
  89. Nexilis.dispatch = nil
  90. if !result {
  91. DispatchQueue.main.async {
  92. Utils.showAlert(title: "Failed to get Master Key".localized(), message: "Biometric authentication hasn't been set up/Biometric invalid.".localized())
  93. }
  94. throw NSError(domain: "KeychainError", code: -99, userInfo: nil)
  95. }
  96. }
  97. let query: [String: Any] = [
  98. kSecClass as String: kSecClassKey,
  99. kSecAttrApplicationTag as String: keyAlias,
  100. kSecReturnData as String: true
  101. ]
  102. var item: CFTypeRef?
  103. let status = SecItemCopyMatching(query as CFDictionary, &item)
  104. guard status == errSecSuccess else {
  105. throw NSError(domain: "KeychainError", code: Int(status), userInfo: nil)
  106. }
  107. guard let keyData = item as? Data else {
  108. throw NSError(domain: "KeyRetrievalError", code: -1, userInfo: nil)
  109. }
  110. return SymmetricKey(data: keyData)
  111. }
  112. func getPrefsKey() throws -> SymmetricKey {
  113. let query: [String: Any] = [
  114. kSecClass as String: kSecClassKey,
  115. kSecAttrApplicationTag as String: prefsKeyAlias,
  116. kSecReturnData as String: true
  117. ]
  118. var item: CFTypeRef?
  119. let status = SecItemCopyMatching(query as CFDictionary, &item)
  120. guard status == errSecSuccess else {
  121. throw NSError(domain: "KeychainError", code: Int(status), userInfo: nil)
  122. }
  123. guard let keyData = item as? Data else {
  124. throw NSError(domain: "KeyRetrievalError", code: -1, userInfo: nil)
  125. }
  126. return SymmetricKey(data: keyData)
  127. }
  128. func encryptP(data: Data) throws -> Data {
  129. let key = try getPrefsKey()
  130. let sealedBox = try AES.GCM.seal(data, using: key)
  131. return sealedBox.combined!
  132. }
  133. func decryptP(data: Data) throws -> Data {
  134. let key = try getPrefsKey()
  135. let sealedBox = try AES.GCM.SealedBox(combined: data)
  136. return try AES.GCM.open(sealedBox, using: key)
  137. }
  138. func encryptD(data: Data) throws -> Data {
  139. let key = try getMasterKey()
  140. let sealedBox = try AES.GCM.seal(data, using: key)
  141. return sealedBox.combined!
  142. }
  143. // Decrypt data
  144. func decryptD(data: Data) throws -> Data {
  145. let key = try getMasterKey()
  146. let sealedBox = try AES.GCM.SealedBox(combined: data)
  147. return try AES.GCM.open(sealedBox, using: key)
  148. }
  149. }