APP安全機制(十六) —— Keychain Services API使用簡單示例(三)

版本記錄

版本號 時間
V1.0 2019.01.01 星期二

前言

在這個信息爆炸的年代,特別是一些敏感的行業,比如金融業和銀行卡相關等等,這都對app的安全機制有更高的需求,很多大公司都有安全 部門,用于檢測自己產品的安全性,但是及時是這樣,安全問題仍然被不斷曝出,接下來幾篇我們主要說一下app的安全機制。感興趣的看我上面幾篇。
1. APP安全機制(一)—— 幾種和安全性有關的情況
2. APP安全機制(二)—— 使用Reveal查看任意APP的UI
3. APP安全機制(三)—— Base64加密
4. APP安全機制(四)—— MD5加密
5. APP安全機制(五)—— 對稱加密
6. APP安全機制(六)—— 非對稱加密
7. APP安全機制(七)—— SHA加密
8. APP安全機制(八)—— 偏好設置的加密存儲
9. APP安全機制(九)—— 基本iOS安全之鑰匙鏈和哈希(一)
10. APP安全機制(十)—— 基本iOS安全之鑰匙鏈和哈希(二)
11. APP安全機制(十一)—— 密碼工具:提高用戶安全性和體驗(一)
12. APP安全機制(十二)—— 密碼工具:提高用戶安全性和體驗(二)
13. APP安全機制(十三)—— 密碼工具:提高用戶安全性和體驗(三)
14. APP安全機制(十四) —— Keychain Services API使用簡單示例(一)
15. APP安全機制(十五) —— Keychain Services API使用簡單示例(二)

源碼

1. Swift

首先看下工程結構

下面就是源碼

1. SecureStore.h
#import <UIKit/UIKit.h>

//! Project version number for SecureStore.
FOUNDATION_EXPORT double SecureStoreVersionNumber;

//! Project version string for SecureStore.
FOUNDATION_EXPORT const unsigned char SecureStoreVersionString[];

// In this header, you should import all the public headers of your framework using statements like #import <SecureStore/PublicHeader.h>
2. SecureStore.swift
import Foundation
import Security

public struct SecureStore {
  let secureStoreQueryable: SecureStoreQueryable
  
  public init(secureStoreQueryable: SecureStoreQueryable) {
    self.secureStoreQueryable = secureStoreQueryable
  }
  
  public func setValue(_ value: String, for userAccount: String) throws {
    guard let encodedPassword = value.data(using: .utf8) else {
      throw SecureStoreError.string2DataConversionError
    }
    
    var query = secureStoreQueryable.query
    query[String(kSecAttrAccount)] = userAccount
    
    var status = SecItemCopyMatching(query as CFDictionary, nil)
    switch status {
    case errSecSuccess:
      var attributesToUpdate: [String: Any] = [:]
      attributesToUpdate[String(kSecValueData)] = encodedPassword
      
      status = SecItemUpdate(query as CFDictionary,
                             attributesToUpdate as CFDictionary)
      if status != errSecSuccess {
        throw error(from: status)
      }
    case errSecItemNotFound:
      query[String(kSecValueData)] = encodedPassword
      
      status = SecItemAdd(query as CFDictionary, nil)
      if status != errSecSuccess {
        throw error(from: status)
      }
    default:
      throw error(from: status)
    }
  }
  
  public func getValue(for userAccount: String) throws -> String? {
    var query = secureStoreQueryable.query
    query[String(kSecMatchLimit)] = kSecMatchLimitOne
    query[String(kSecReturnAttributes)] = kCFBooleanTrue
    query[String(kSecReturnData)] = kCFBooleanTrue
    query[String(kSecAttrAccount)] = userAccount
    
    var queryResult: AnyObject?
    let status = withUnsafeMutablePointer(to: &queryResult) {
      SecItemCopyMatching(query as CFDictionary, $0)
    }
    
    switch status {
    case errSecSuccess:
      guard
        let queriedItem = queryResult as? [String: Any],
        let passwordData = queriedItem[String(kSecValueData)] as? Data,
        let password = String(data: passwordData, encoding: .utf8)
        else {
          throw SecureStoreError.data2StringConversionError
      }
      return password
    case errSecItemNotFound:
      return nil
    default:
      throw error(from: status)
    }
  }
  
  public func removeValue(for userAccount: String) throws {
    var query = secureStoreQueryable.query
    query[String(kSecAttrAccount)] = userAccount
    
    let status = SecItemDelete(query as CFDictionary)
    guard status == errSecSuccess || status == errSecItemNotFound else {
      throw error(from: status)
    }
  }
  
  public func removeAllValues() throws {
    let query = secureStoreQueryable.query
    
    let status = SecItemDelete(query as CFDictionary)
    guard status == errSecSuccess || status == errSecItemNotFound else {
      throw error(from: status)
    }
  }
  
  private func error(from status: OSStatus) -> SecureStoreError {
    let message = SecCopyErrorMessageString(status, nil) as String? ?? NSLocalizedString("Unhandled Error", comment: "")
    return SecureStoreError.unhandledError(message: message)
  }
}
3. SecureStoreQueryable.swift
import Foundation

public protocol SecureStoreQueryable {
  var query: [String: Any] { get }
}

public struct GenericPasswordQueryable {
  let service: String
  let accessGroup: String?
  
  init(service: String, accessGroup: String? = nil) {
    self.service = service
    self.accessGroup = accessGroup
  }
}

extension GenericPasswordQueryable: SecureStoreQueryable {
  public var query: [String: Any] {
    var query: [String: Any] = [:]
    query[String(kSecClass)] = kSecClassGenericPassword
    query[String(kSecAttrService)] = service
    // Access group if target environment is not simulator
    #if !targetEnvironment(simulator)
    if let accessGroup = accessGroup {
      query[String(kSecAttrAccessGroup)] = accessGroup
    }
    #endif
    return query
  }
}

public struct InternetPasswordQueryable {
  let server: String
  let port: Int
  let path: String
  let securityDomain: String
  let internetProtocol: InternetProtocol
  let internetAuthenticationType: InternetAuthenticationType
}

extension InternetPasswordQueryable: SecureStoreQueryable {
  public var query: [String: Any] {
    var query: [String: Any] = [:]
    query[String(kSecClass)] = kSecClassInternetPassword
    query[String(kSecAttrPort)] = port
    query[String(kSecAttrServer)] = server
    query[String(kSecAttrSecurityDomain)] = securityDomain
    query[String(kSecAttrPath)] = path
    query[String(kSecAttrProtocol)] = internetProtocol.rawValue
    query[String(kSecAttrAuthenticationType)] = internetAuthenticationType.rawValue
    return query
  }
}
4. SecureStoreError.swift
import Foundation

public enum SecureStoreError: Error {
  case string2DataConversionError
  case data2StringConversionError
  case unhandledError(message: String)
}

extension SecureStoreError: LocalizedError {
  public var errorDescription: String? {
    switch self {
    case .string2DataConversionError:
      return NSLocalizedString("String to Data conversion error", comment: "")
    case .data2StringConversionError:
      return NSLocalizedString("Data to String conversion error", comment: "")
    case .unhandledError(let message):
      return NSLocalizedString(message, comment: "")
    }
  }
}
5. InternetProtocol.swift
import Foundation

public enum InternetProtocol: RawRepresentable {
  case ftp, ftpAccount, http, irc, nntp, pop3, smtp, socks, imap, ldap, appleTalk, afp, telnet, ssh, ftps, https, httpProxy, httpsProxy, ftpProxy, smb, rtsp, rtspProxy, daap, eppc, ipp, nntps, ldaps, telnetS, imaps, ircs, pop3S
  
  public init?(rawValue: String) {
    switch rawValue {
    case String(kSecAttrProtocolFTP):
      self = .ftp
    case String(kSecAttrProtocolFTPAccount):
      self = .ftpAccount
    case String(kSecAttrProtocolHTTP):
      self = .http
    case String(kSecAttrProtocolIRC):
      self = .irc
    case String(kSecAttrProtocolNNTP):
      self = .nntp
    case String(kSecAttrProtocolPOP3):
      self = .pop3
    case String(kSecAttrProtocolSMTP):
      self = .smtp
    case String(kSecAttrProtocolSOCKS):
      self = .socks
    case String(kSecAttrProtocolIMAP):
      self = .imap
    case String(kSecAttrProtocolLDAP):
      self = .ldap
    case String(kSecAttrProtocolAppleTalk):
      self = .appleTalk
    case String(kSecAttrProtocolAFP):
      self = .afp
    case String(kSecAttrProtocolTelnet):
      self = .telnet
    case String(kSecAttrProtocolSSH):
      self = .ssh
    case String(kSecAttrProtocolFTPS):
      self = .ftps
    case String(kSecAttrProtocolHTTPS):
      self = .https
    case String(kSecAttrProtocolHTTPProxy):
      self = .httpProxy
    case String(kSecAttrProtocolHTTPSProxy):
      self = .httpsProxy
    case String(kSecAttrProtocolFTPProxy):
      self = .ftpProxy
    case String(kSecAttrProtocolSMB):
      self = .smb
    case String(kSecAttrProtocolRTSP):
      self = .rtsp
    case String(kSecAttrProtocolRTSPProxy):
      self = .rtspProxy
    case String(kSecAttrProtocolDAAP):
      self = .daap
    case String(kSecAttrProtocolEPPC):
      self = .eppc
    case String(kSecAttrProtocolIPP):
      self = .ipp
    case String(kSecAttrProtocolNNTPS):
      self = .nntps
    case String(kSecAttrProtocolLDAPS):
      self = .ldaps
    case String(kSecAttrProtocolTelnetS):
      self = .telnetS
    case String(kSecAttrProtocolIMAPS):
      self = .imaps
    case String(kSecAttrProtocolIRCS):
      self = .ircs
    case String(kSecAttrProtocolPOP3S):
      self = .pop3S
    default:
      self = .http
    }
  }
  
  public var rawValue: String {
    switch self {
    case .ftp:
      return String(kSecAttrProtocolFTP)
    case .ftpAccount:
      return String(kSecAttrProtocolFTPAccount)
    case .http:
      return String(kSecAttrProtocolHTTP)
    case .irc:
      return String(kSecAttrProtocolIRC)
    case .nntp:
      return String(kSecAttrProtocolNNTP)
    case .pop3:
      return String(kSecAttrProtocolPOP3)
    case .smtp:
      return String(kSecAttrProtocolSMTP)
    case .socks:
      return String(kSecAttrProtocolSOCKS)
    case .imap:
      return String(kSecAttrProtocolIMAP)
    case .ldap:
      return String(kSecAttrProtocolLDAP)
    case .appleTalk:
      return String(kSecAttrProtocolAppleTalk)
    case .afp:
      return String(kSecAttrProtocolAFP)
    case .telnet:
      return String(kSecAttrProtocolTelnet)
    case .ssh:
      return String(kSecAttrProtocolSSH)
    case .ftps:
      return String(kSecAttrProtocolFTPS)
    case .https:
      return String(kSecAttrProtocolHTTPS)
    case .httpProxy:
      return String(kSecAttrProtocolHTTPProxy)
    case .httpsProxy:
      return String(kSecAttrProtocolHTTPSProxy)
    case .ftpProxy:
      return String(kSecAttrProtocolFTPProxy)
    case .smb:
      return String(kSecAttrProtocolSMB)
    case .rtsp:
      return String(kSecAttrProtocolRTSP)
    case .rtspProxy:
      return String(kSecAttrProtocolRTSPProxy)
    case .daap:
      return String(kSecAttrProtocolDAAP)
    case .eppc:
      return String(kSecAttrProtocolEPPC)
    case .ipp:
      return String(kSecAttrProtocolIPP)
    case .nntps:
      return String(kSecAttrProtocolNNTPS)
    case .ldaps:
      return String(kSecAttrProtocolLDAPS)
    case .telnetS:
      return String(kSecAttrProtocolTelnetS)
    case .imaps:
      return String(kSecAttrProtocolIMAPS)
    case .ircs:
      return String(kSecAttrProtocolIRCS)
    case .pop3S:
      return String(kSecAttrProtocolPOP3S)
    }
  }
}
6. InternetAuthenticationType.swift
import Foundation

public enum InternetAuthenticationType: RawRepresentable {
  case ntlm, msn, dpa, rpa, httpBasic, httpDigest, htmlForm, `default`
  
  public init?(rawValue: String) {
    switch rawValue {
    case String(kSecAttrAuthenticationTypeNTLM):
      self = .ntlm
    case String(kSecAttrAuthenticationTypeMSN):
      self = .msn
    case String(kSecAttrAuthenticationTypeDPA):
      self = .dpa
    case String(kSecAttrAuthenticationTypeRPA):
      self = .rpa
    case String(kSecAttrAuthenticationTypeHTTPBasic):
      self = .httpBasic
    case String(kSecAttrAuthenticationTypeHTTPDigest):
      self = .httpDigest
    case String(kSecAttrAuthenticationTypeHTMLForm):
      self = .htmlForm
    case String(kSecAttrAuthenticationTypeDefault):
      self = .default
    default:
      self = .default
    }
  }
  
  public var rawValue: String {
    switch self {
    case .ntlm:
      return String(kSecAttrAuthenticationTypeNTLM)
    case .msn:
      return String(kSecAttrAuthenticationTypeMSN)
    case .dpa:
      return String(kSecAttrAuthenticationTypeDPA)
    case .rpa:
      return String(kSecAttrAuthenticationTypeRPA)
    case .httpBasic:
      return String(kSecAttrAuthenticationTypeHTTPBasic)
    case .httpDigest:
      return String(kSecAttrAuthenticationTypeHTTPDigest)
    case .htmlForm:
      return String(kSecAttrAuthenticationTypeHTMLForm)
    case .default:
      return String(kSecAttrAuthenticationTypeDefault)
    }
  }
}
7. SecureStoreTests.swift
import XCTest
@testable import SecureStore

class SecureStoreTests: XCTestCase {
  var secureStoreWithGenericPwd: SecureStore!
  var secureStoreWithInternetPwd: SecureStore!
  
  override func setUp() {
    super.setUp()
    
    let genericPwdQueryable = GenericPasswordQueryable(service: "MyService")
    secureStoreWithGenericPwd = SecureStore(secureStoreQueryable: genericPwdQueryable)
    
    let internetPwdQueryable = InternetPasswordQueryable(server: "someServer",
                                                         port: 8080,
                                                         path: "somePath",
                                                         securityDomain: "someDomain",
                                                         internetProtocol: .https,
                                                         internetAuthenticationType: .httpBasic)
    secureStoreWithInternetPwd = SecureStore(secureStoreQueryable: internetPwdQueryable)
  }

  override func tearDown() {
    try? secureStoreWithGenericPwd.removeAllValues()
    try? secureStoreWithInternetPwd.removeAllValues()

    super.tearDown()
  }
  
  func testSaveGenericPassword() {
    do {
      try secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword")
    } catch (let e) {
      XCTFail("Saving generic password failed with \(e.localizedDescription).")
    }
  }
  
  func testReadGenericPassword() {
    do {
      try secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword")
      let password = try secureStoreWithGenericPwd.getValue(for: "genericPassword")
      XCTAssertEqual("pwd_1234", password)
    } catch (let e) {
      XCTFail("Reading generic password failed with \(e.localizedDescription).")
    }
  }
  
  func testUpdateGenericPassword() {
    do {
      try secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword")
      try secureStoreWithGenericPwd.setValue("pwd_1235", for: "genericPassword")
      let password = try secureStoreWithGenericPwd.getValue(for: "genericPassword")
      XCTAssertEqual("pwd_1235", password)
    } catch (let e) {
      XCTFail("Updating generic password failed with \(e.localizedDescription).")
    }
  }
  
  func testRemoveGenericPassword() {
    do {
      try secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword")
      try secureStoreWithGenericPwd.removeValue(for: "genericPassword")
      XCTAssertNil(try secureStoreWithGenericPwd.getValue(for: "genericPassword"))
    } catch (let e) {
      XCTFail("Saving generic password failed with \(e.localizedDescription).")
    }
  }
  
  func testRemoveAllGenericPasswords() {
    do {
      try secureStoreWithGenericPwd.setValue("pwd_1234", for: "genericPassword")
      try secureStoreWithGenericPwd.setValue("pwd_1235", for: "genericPassword2")
      try secureStoreWithGenericPwd.removeAllValues()
      XCTAssertNil(try secureStoreWithGenericPwd.getValue(for: "genericPassword"))
      XCTAssertNil(try secureStoreWithGenericPwd.getValue(for: "genericPassword2"))
    } catch (let e) {
      XCTFail("Removing generic passwords failed with \(e.localizedDescription).")
    }
  }
  
  func testSaveInternetPassword() {
    do {
      try secureStoreWithInternetPwd.setValue("pwd_1234", for: "internetPassword")
    } catch (let e) {
      XCTFail("Saving Internet password failed with \(e.localizedDescription).")
    }
  }
  
  func testReadInternetPassword() {
    do {
      try secureStoreWithInternetPwd.setValue("pwd_1234", for: "internetPassword")
      let password = try secureStoreWithInternetPwd.getValue(for: "internetPassword")
      XCTAssertEqual("pwd_1234", password)
    } catch (let e) {
      XCTFail("Reading Internet password failed with \(e.localizedDescription).")
    }
  }
  
  func testUpdateInternetPassword() {
    do {
      try secureStoreWithInternetPwd.setValue("pwd_1234", for: "internetPassword")
      try secureStoreWithInternetPwd.setValue("pwd_1235", for: "internetPassword")
      let password = try secureStoreWithInternetPwd.getValue(for: "internetPassword")
      XCTAssertEqual("pwd_1235", password)
    } catch (let e) {
      XCTFail("Updating Internet password failed with \(e.localizedDescription).")
    }
  }
  
  func testRemoveInternetPassword() {
    do {
      try secureStoreWithInternetPwd.setValue("pwd_1234", for: "internetPassword")
      try secureStoreWithInternetPwd.removeValue(for: "internetPassword")
      XCTAssertNil(try secureStoreWithInternetPwd.getValue(for: "internetPassword"))
    } catch (let e) {
      XCTFail("Removing Internet password failed with \(e.localizedDescription).")
    }
  }
  
  func testRemoveAllInternetPasswords() {
    do {
      try secureStoreWithInternetPwd.setValue("pwd_1234", for: "internetPassword")
      try secureStoreWithInternetPwd.setValue("pwd_1235", for: "internetPassword2")
      try secureStoreWithInternetPwd.removeAllValues()
      XCTAssertNil(try secureStoreWithInternetPwd.getValue(for: "internetPassword"))
      XCTAssertNil(try secureStoreWithInternetPwd.getValue(for: "internetPassword2"))
    } catch (let e) {
      XCTFail("Removing Internet passwords failed with \(e.localizedDescription).")
    }
  }
}

后記

本篇主要講述了Keychain Services API使用簡單示例,感興趣的給個贊或者關注~~~

?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容