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

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 217,907评论 6 506
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,987评论 3 395
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 164,298评论 0 354
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,586评论 1 293
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,633评论 6 392
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,488评论 1 302
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,275评论 3 418
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,176评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,619评论 1 314
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,819评论 3 336
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,932评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,655评论 5 346
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,265评论 3 329
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,871评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,994评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,095评论 3 370
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,884评论 2 354

推荐阅读更多精彩内容