Modern Swift wrapper for Keychain Services API with the benefits of static typing

Overview

SwiftyKeychainKit

Platforms Build Status Swift version CocoaPods compatible SPM compatible Carthage compatible

SwiftyKeychainKit is a simple Swift wrapper for Keychain Services API with the benefits of static typing. Define your keys in one place, use value types easily, and get extra safety and convenient compile-time checks for free.

Features

  • Static typing and compile-time checks
  • Support Gereric and Internet passwords
  • Throwing and Result type get methods
  • Easy way to implement support for custom types

Usage

Basic

let keychain = Keychain(service: "com.swifty.keychain")
let accessTokenKey = KeychainKey<String>(key: "accessToken")

// Save or modify value
try? keychain.save("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9", for : accessTokenKey)

// Get value 
let value = try keychain.get(accessTokenKey)

// Remove value 
try keychain.remove(accessTokenKey)

// Remove all values 
try keychain.removeAll()

Instantiation

// Generic password
let keychain = Keychain(service: "com.swifty.keychainkit")

// Internet password
let keychain = Keychain(server: URL(string: "https://www.google.com")!, protocolType: .https)

Define keys

For extra convenience, define your keys by extending KeychainKeys class and adding static properties:

extension KeychainKeys {
    static let username = KeychainKey<String>(key: "username")
    static let age = KeychainKey<Int>(key: "age")
}

and later in the code use shortcut dot syntax:

// save
try? keychain.save("John Snow", for: .username)

// get
let username = try keychain.get(.username)

Geting values

You can use subscripts and dynamicCallable syntax sugar to get value as Result<ValueType, KeychainError>

let username = try keychain[.username].get()

// or 

if case .success(let age) = keychain[.age] {
    ...
}
let username = try keychain(.username).get()

// or 

if case .success(let age) = keychain(.age) {
    ...
}

Both subscripts and dynamicCallable syntaxt available only for geting values. Currently Swift language limitation do not allow implement setter with error handling.

Default values

You can provide default value for get method and it will used than keychain key is nil and no error throw.

try keychain.get(.username, default: "Daenerys Targaryen")

// or

try keychain[.age, default: 18].get() 

Supported types

  • Int
  • String
  • Double
  • Float
  • Bool
  • Data

Codable

struct MyStruct: Codable, KeychainSerializable { ... }

NSCoding

class MyClass: NSObject, NSCoding, KeychainSerializable { ... }

Custom types

In order to save/get your own custom type that we don't support, you need to confirm it KeychainSerializable and implement KeychainBridge for this type.

As an example saving Array<String> using JSONSerialization:

extension Array: KeychainSerializable where Element == String  {
    public static var bridge: KeychainBridge<[String]> { return KeychainBridgeStringArray() }
}
class KeychainBridgeStringArray: KeychainBridge<[String]> {
    public override func set(_ value: [String], forKey key: String, in keychain: Keychain) throws {
        guard let data = try? JSONSerialization.data(withJSONObject: value, options: []) else {
            fatalError()
        }
        try? persist(value: data, key: key, keychain: keychain)
    }

    public override func get(key: String, from keychain: Keychain) throws -> [String]? {
        guard let data = try? find(key: key, keychain: keychain) else {
            return nil
        }

        return (try? JSONSerialization.jsonObject(with: data, options: [])) as? [String]
    }
}

Supported attributes

Common

  • kSecAttrAccessGroup
  • kSecAttrAccessible
  • kSecAttrDescription
  • kSecAttrComment
  • kSecAttrCreator
  • kSecAttrType
  • kSecAttrLabel
  • kSecAttrIsInvisible
  • kSecAttrIsNegative
  • kSecAttrAccount
  • kSecAttrSynchronizable

Generic password

  • kSecAttrAccessControl
  • kSecAttrService
  • kSecAttrGeneric

Internet password

  • kSecAttrSecurityDomain
  • kSecAttrServer
  • kSecAttrProtocol
  • kSecAttrAuthenticationType
  • kSecAttrPort
  • kSecAttrPath

Requirement

Swift version 5.0

Platform Availability
iOS >= 8.0
macOS -
tvOS -
watchOS -

Installation

CocoaPods

pod 'SwiftyKeychainKit', '1.0.0-beta.2'

Swift Package Manager

let package = Package(
    dependencies: [
        .Package(url: "https://github.com/andriyslyusar/SwiftyKeychainKit.git", .exact("1.0.0-beta.2"))
    ]
)

Carthage

github "andriyslyusar/SwiftyKeychainKit" "1.0.0-beta.2"

Acknowledgement

Author

Andriy Slyusar

License

SwiftyKeychainKit is available under the MIT license. See the LICENSE file for more info.

You might also like...
Example of using TOTP with iCloud Keychain in iOS 15

Installation This example needs Ngrok and Ruby 3.0.3+. Setup project with Makefi

A tool to check which keychain items are available to an attacker once an iOS device has been jailbroken

Keychain Dumper Usage All that should be needed to use keychain_dumper is the binary that is checked in to the Keychain-Dumper Git repository. This bi

Generating OTP one-time passwords in Swift.
Generating OTP one-time passwords in Swift.

One Time Password Navigate Installation Swift Package Manager CocoaPods Manually Usage Apps Using Installation Ready to use on iOS 13+, tvOS 13+ & wat

Safely access Apple's SF Symbols using static typing
Safely access Apple's SF Symbols using static typing

Supported Versions • Motivation • Installation • Usage • Contributing • License • Issues • Pull Requests Supported Versions SFSafeSymbols supports mul

Keychain - Keychain wrapper with swift

Keychain wrapper. Store a value as a generic password: let account = "an-arbitra

UICKeyChainStore is a simple wrapper for Keychain on iOS, watchOS, tvOS and macOS. Makes using Keychain APIs as easy as NSUserDefaults.

UICKeyChainStore UICKeyChainStore is a simple wrapper for Keychain that works on iOS and OS X. Makes using Keychain APIs as easy as NSUserDefaults. Lo

A Layer-2 framework built over Keychain API which helps in using Keychain in all your Apple devices with easiness and flexibility.
A Layer-2 framework built over Keychain API which helps in using Keychain in all your Apple devices with easiness and flexibility.

Keychain Manager Keychain Manager is a Layer-2 framework built over Keychain API which helps in using Keychain in all your Apple devices with easiness

ChidoriMenu - An easy way to add menus visually similar to iOS 14's Pull Down and Context Menus but with some added benefits
ChidoriMenu - An easy way to add menus visually similar to iOS 14's Pull Down and Context Menus but with some added benefits

ChidoriMenu 🐦 ⚡️ An easy way to add popover menus visually similar to the Conte

Valet lets you securely store data in the iOS, tvOS, or macOS Keychain without knowing a thing about how the Keychain works.

Valet Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy.

Valet lets you securely store data in the iOS, tvOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy. We promise.

Valet Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy.

Swift CLI for strong-typing images, colors, storyboards, fonts and localizations

Shark Shark is a Swift command line tool that generates type safe enums for your images, colors, storyboards, fonts and localizations. Because Shark r

Demonstration code for a simple Swift property-wrapper, keypath-based dependency injection system. The keypaths ensure compile-time safety for all injectable services.

Injectable Demo Preliminary musings and demonstration code for a simple Swift property-wrapper, keypath-based dependency injection system. The keypath

Very simple swift wrapper for Biometric Authentication Services (Touch ID) on iOS.

SimpleTouch Very simple swift wrapper for Biometric Authentication Services (Touch ID) on iOS. Sample Project There is a SimpleTouchDemo target define

UITextField realtime currency formatter - format while typing

Objective-C Realtime Currency Formatter An extremely simple Objective-C class for formatting currencies. Ready to work with the UITextFieldDelegate an

Subclass of UITextField that shows inline suggestions while typing.
Subclass of UITextField that shows inline suggestions while typing.

AutocompleteField Subclass of UITextField that shows inline suggestions while typing. Plug and play replacement for UITextField. Delimiter support. Pe

TextFormation - Rules system for live typing completions

TextFormation TextFormation is simple rule system that can be used to implement

A modern Swift wrapper for Instagram Private API.
A modern Swift wrapper for Instagram Private API.

Swiftagram is a wrapper for Instagram Private API, written entirely in (modern) Swift. Instagram's official APIs, both the Instagram Basic Display API

Simple Swift wrapper for Keychain that works on iOS, watchOS, tvOS and macOS.
Simple Swift wrapper for Keychain that works on iOS, watchOS, tvOS and macOS.

KeychainAccess KeychainAccess is a simple Swift wrapper for Keychain that works on iOS and OS X. Makes using Keychain APIs extremely easy and much mor

A simple Swift Keychain Wrapper for iOS, watchOS, and OS X.

Latch A simple Swift 2.0 Keychain Wrapper for iOS, watchOS 2, and OS X. Usage A proper example of how to use Latch can be seen in the tests. import La

Comments
  • Increase deployment target and add all supported platforms

    Increase deployment target and add all supported platforms

    • Increase deployment target to iOS 10 to silence warning that it has to be at least 9
    • Added tvOS, watchOS, macOS and Catalyst platforms to Package.swift
    • Increased Swift Tools Version to 5.5 in Package.swift
    opened by EmilioPelaez 1
  • Use keychain key as primary holder of attributes

    Use keychain key as primary holder of attributes

    • Use keychain key as primary holder of attributes
    • Use enum to isolate generic and internet password properties, leave only accessGroup as keychain defined parameter
    opened by andriyslyusar 0
  • Great project - Need help with a SwiftUI Property Wrapper for this.

    Great project - Need help with a SwiftUI Property Wrapper for this.

    Hi, Just wondering if its easily possible to write a SwiftUI property wrapper for this Keychain library? I've had an attempt but can't get it quite right.

    struct Secret: Codable, KeychainSerializable {
        var pin: String?
        var mnemonic: String?
        var publicKey: String?
        var privateKey: String?
    }
    
    @SwiftyKeychain(key: Constants.Keychain.secret, defaultValue: Secret())
    var secret: Secret?
    

    Or

    @SwiftyKeychain(key: Constants.Keychain.secret)
    var secret: Secret = Secret()
    

    Thank you.

    opened by waelsaad 1
Releases(1.0.0-beta.2)
Owner
Andriy Slyusar
Andriy Slyusar
UICKeyChainStore is a simple wrapper for Keychain on iOS, watchOS, tvOS and macOS. Makes using Keychain APIs as easy as NSUserDefaults.

UICKeyChainStore UICKeyChainStore is a simple wrapper for Keychain that works on iOS and OS X. Makes using Keychain APIs as easy as NSUserDefaults. Lo

Kishikawa Katsumi 3.1k Dec 28, 2022
A Layer-2 framework built over Keychain API which helps in using Keychain in all your Apple devices with easiness and flexibility.

Keychain Manager Keychain Manager is a Layer-2 framework built over Keychain API which helps in using Keychain in all your Apple devices with easiness

Gokul Nair 14 Jan 1, 2023
Valet lets you securely store data in the iOS, tvOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy. We promise.

Valet Valet lets you securely store data in the iOS, tvOS, watchOS, or macOS Keychain without knowing a thing about how the Keychain works. It’s easy.

Square 3.8k Jan 4, 2023
Simple Swift wrapper for Keychain that works on iOS, watchOS, tvOS and macOS.

KeychainAccess KeychainAccess is a simple Swift wrapper for Keychain that works on iOS and OS X. Makes using Keychain APIs extremely easy and much mor

Kishikawa Katsumi 7.2k Jan 5, 2023
A simple wrapper for the iOS Keychain to allow you to use it in a similar fashion to User Defaults. Written in Swift.

SwiftKeychainWrapper A simple wrapper for the iOS / tvOS Keychain to allow you to use it in a similar fashion to User Defaults. Written in Swift. Prov

Jason 1.5k Jan 8, 2023
A keychain wrapper that is so easy to use that your cat could use it.

A keychain wrapper that is so easy to use that your cat could use it.

HyperRedink 71 Oct 15, 2022
Simple Objective-C wrapper for the keychain that works on Mac and iOS

SAMKeychain SAMKeychain is a simple wrapper for accessing accounts, getting passwords, setting passwords, and deleting passwords using the system Keyc

Sam Soffes 5.4k Jan 8, 2023
A powerful, protocol-oriented library for working with the keychain in Swift.

Locksmith A powerful, protocol-oriented library for working with the keychain in Swift. ?? iOS 8.0+ ?? Mac OS X 10.10+ ⌚️ watchOS 2 ?? tvOS ?? I make

Matthew Palmer 2.9k Dec 21, 2022
Recover lost keychain passwords with swift

brutalkeychain Recover lost keychain passwords using a simple swift script (so c

Charles Edge 9 Sep 12, 2022
Recover lost keychain passwords with swift

brutalkeychain Recover lost keychain passwords using a simple swift script (so c

Charles Edge 4 Dec 24, 2021