美文网首页APP安全学习
APP安全机制(十六) —— Keychain Services

APP安全机制(十六) —— Keychain Services

作者: 刀客传奇 | 来源:发表于2019-01-01 15:34 被阅读71次

    版本记录

    版本号 时间
    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使用简单示例,感兴趣的给个赞或者关注~~~

    相关文章

      网友评论

        本文标题:APP安全机制(十六) —— Keychain Services

        本文链接:https://www.haomeiwen.com/subject/ijvnlqtx.html