Demonstration library for using the Secure Enclave on iOS

Overview

SecureEnclaveCrypto

This project shows you how to

  • create a keypair where as the private key is stored in the secure enclave
  • sign a string / some data with the private key
  • use the security functions like SecKeyRawVerify, SecKeyGeneratePair and SecItemCopyMatching in Swift 3 and Objective-C
  • store the public key in the keychain

Apple quietly released a new API in iOS 9 (kSecAttrTokenIDSecureEnclave) that allowed developers to create and use keys stored directly in the Secure Enclave (see "Security and Your Apps" starting from slide 195). This feature opens enormous possibilities for security by enabling applications to use private keys that are safely stored outside of iOS and away from any potential malware.

We tried to use this API shortly after it was released and found it lacking: the required attribute was entirely undocumented, the key format is not compatible with OpenSSL, and Apple didn't even say what cipher suite was used (it's secp256r1). The code in this repository is an attempt to fix these issues by providing an easy-to-use wrapper around the Secure Enclave Crypto API.

Show me the code

This project thus contains two codebases, one in Swift (from @hfossli) and one in Objective-C which show how to use this API for basic functionality. Both directories contain a README.md file with more specific documentation.

Creating OpenSSL-compatible public key

The public key returned from the Secure Enclave can be fed to key_builder.rb to create an OpenSSL-compatible representation of the ECC public key. The key_builder.rb script takes one parameter: the public key as hex / base 16.

$ ruby key_builder.rb "045ac9bd 7c4d8e77 b37fd14f bf2822ac 4ad4d62f 1bce4019 60bdbdc7 1102da0c 78603266 7dd0fe8b 2a847135 1d1d0e01 a2cd019e ab9c4b7c 9a3fed15 1f20bcc2 9a"

-----BEGIN PUBLIC KEY-----
MFkwEwYHKoZIzj0CAQYIKoZIzj0DAQcDQgAEsng2kkyuVVqyK1BRo8EZhJTM
Mubz1P4MvF6TVwmnbCEUGv4IssA8FXqNb2txbLtlYvNiJPjss/62HKMvR2tm
uA==
-----END PUBLIC KEY-----
Comments
  • Verify signature

    Verify signature

    Okay, so it's easy to verify the signature using the public key (SecKeyRef / SecKey) reference retreived from security framework. I want to eat my own dogfood and verify the signature using the public key hex string. Any ideas how I can do that?

    opened by hfossli 18
  • Add ECIES encryption and decryption support.

    Add ECIES encryption and decryption support.

    The decryption API only works on iOS 10.3 and above. I was told it being broken was a bug (rdar://problem/29438764), and it appears to work in the latest beta.

    Usage is pretty straightforward:

    let encrypted = try Manager.shared.encrypt("Hello!".data(using: .utf8)!)
    let decrypted = try Manager.shared.decrypt(encrypted) // "Hello!"
    

    Uses SHA256 for the KDF which should be a sane default.

    opened by iangcarroll 12
  • New library

    New library

    I did a total rewrite from ground up and made a new library: https://github.com/agens-no/EllipticCurveKeyPair

    I decided to not send a pull request in to this repo because the company I work for is paying for my hours and up until now and I did all the heavy lifting with swift version anyway. I don't violate any license as I wrote everything from ground up.

    Thanks for all support! If you'd like to join as contributors to this repo you are more than welcome.

    Compared to the swift code in this repo

    • better structure and api
    • better error handling
    • exporting the public key properly
    • signature validates with openssl command (was missing sha256)
    • useful copy paste output for validating signatures easily in console
    • fallback to keychain on simulator for faster development

    I hope you like it ✨

    opened by hfossli 3
  • Clarify TouchID vs. device passcode use cases

    Clarify TouchID vs. device passcode use cases

    The sample code currently shows only the TouchID use case, even though in the implementation of KeyInterface there is a generatePasscodeKeyPair method, but it is not exposed publicly.

    As far as I understand it (correct me if I'm wrong), you can also use the passcode as authentication to protect the private key. The private key will still be non-extractable and stored in the secure enclave. The main drawback I see here is that by using the device passcode instead of TouchID is that the passcode is entered by the user through a UI and thus passes through the user space and kernel space, whereas the TouchID interaction will remain completely in the secure enclave.

    I think you should either mention this as a (less secure) option or drop the generatePasscodeKeyPair method in the implementation altogether.

    opened by suzukieng 2
  • Example doesn't run in Xcode simulator

    Example doesn't run in Xcode simulator

    I'm trying to get the example running on the Xcode IOS simulator and am getting an exception here. The exception is Thread 1: EXC_BAD_ACCESS (code=1, address=0x10). It seems that lookupPrivateKeyRef is returning nil here and generateKeyPairWithAccessControlObject is returning false here. I'm not used to working with iOS stuff, so I'm not really sure how to debug this further.

    I've tried running another SEC example, but get a parameter error (-50) from SecKeyGeneratePair. I'm wondering if SEC doesn't work at all in the iOS simulator?

    Any help would be appreciated. I'm running

    • Xcode: Version 7.3.1
    • Simulator: iPhone 6s / iOS 9.3 (13E230)

    Let me know if I can provide any other debugging output or information.

    opened by btoews 1
  • The accessibility of items when passcode change

    The accessibility of items when passcode change

    What will happen to the items with access kSecAttrAccessibleWhenPasscodeSetThisDeviceOnly if the passcode has been changed? Are they still accessible? Thanks

    opened by openluopworld 0
  • icloud restore vs transfer from another iphone directly

    icloud restore vs transfer from another iphone directly

    Hi, How do i identify and delete the secure encalve key when i use transfer from another iphone directly, icloud restore erases keychain value , so i am able to identify if it is restored from icloud in another phone but it is not getting cleared when i use transfer from another iphone directly, so how to clear secure encalve private keys? any idea?

    opened by GManShen 0
  • encrypting/decrypting

    encrypting/decrypting

    According to Working with Secure Enclave, we can use kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM to do AES/GCM with a symmetric key that's wrapped by asymmetric (ECIES) encryption.

    In investigating this, I added the following to generateKeyPairWithAccessControlObject of SecureEnclaveObjective-C:

      // kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM uses kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA1
      BOOL canKeyExchange = SecKeyIsAlgorithmSupported(privateKeyRef,
                                                       kSecKeyOperationTypeKeyExchange,
                                                       kSecKeyAlgorithmECDHKeyExchangeCofactorX963SHA1);
      NSLog(@"canKeyExchange %d", canKeyExchange);
        
      BOOL canEncrypt = SecKeyIsAlgorithmSupported(publicKeyRef,
                                                   kSecKeyOperationTypeEncrypt,
                                                   kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM);
      NSLog(@"canEncrypt %d", canEncrypt);
        
      BOOL canDecrypt = SecKeyIsAlgorithmSupported(privateKeyRef,
                                                   kSecKeyOperationTypeDecrypt,
                                                   kSecKeyAlgorithmECIESEncryptionCofactorX963SHA256AESGCM);
      NSLog(@"canDecrypt %d", canDecrypt);
    

    which shows

    canKeyExchange 1
    canEncrypt 1
    canDecrypt 0
    

    I'm rather baffled by this-- how can encryption be supported while decryption isn't?

    opened by paleozogt 3
  • Investigate SE Crypto capabilities of the new MacBooks

    Investigate SE Crypto capabilities of the new MacBooks

    The new MacBookPros have a secure display (Touchbar) and TouchID. We should investigate the applicability of this project and port this project to the new MacBooks.

    opened by withzombies 1
  • Use SecKeyCopyExternalRepresentation to export public keys

    Use SecKeyCopyExternalRepresentation to export public keys

    Apple added a new API to export keys in sane formats. We should use it.

    https://developer.apple.com/reference/security/1643698-seckeycopyexternalrepresentation

    opened by withzombies 12
Owner
Trail of Bits
More code: binary lifters @lifting-bits, blockchain @crytic
Trail of Bits
Secure your app by obfuscating all the hard-coded security-sensitive strings.

App Obfuscator for iOS Apps Secure your app by obfuscating all the hard-coded security-sensitive strings. Security Sensitive strings can be: REST API

pj 601 Dec 16, 2022
CryptoSwift is a growing collection of standard and secure cryptographic algorithms implemented in Swift

CryptoSwift Crypto related functions and helpers for Swift implemented in Swift. (#PureSwift) Note: The main branch follows the latest currently relea

Marcin Krzyzanowski 9.4k Jan 9, 2023
Simple and secure hashing in Swift with the SipHash algorithm

SipHash ⚠️ WARNING This package has been obsoleted by the Hasher type and the Hashable.hash(into:) requirement introduced in Swift 4.2. Using this pac

null 262 Dec 19, 2022
A tiny and easy to use Swift class to encrypt strings using HMAC algorithms.

#Sweet HMAC SweetHMAC is a tiny and easy to use Swift class to encrypt strings using HMAC algorithms. A special thanks to jernejstrasner for shared HM

Jan Cássio 37 Jul 27, 2022
A wrapper for Apple's Common Crypto library written in Swift.

IDZSwiftCommonCrypto A Swift wrapper for Apple's CommonCrypto library. IDZSwiftCommonCrypto works with both CocoaPods and Cathage. For more details on

idz 472 Dec 12, 2022
BitWiser - A simple library to help you in dealing with bytes, bits and nibbles

BitWiser Bitwiser is a collection of methods and properties that makes you work

Andrea Finollo 19 Dec 27, 2022
RSA public/private key generation, RSA, AES encryption/decryption, RSA sign/verify in Swift with CommonCrypto in iOS and OS X

SwCrypt Create public and private RSA keys in DER format let (privateKey, publicKey) = try! CC.RSA.generateKeyPair(2048) Convert them to PEM format l

soyer 695 Dec 8, 2022
Safe and easy to use crypto for iOS and macOS

Swift-Sodium Swift-Sodium provides a safe and easy to use interface to perform common cryptographic operations on macOS, iOS, tvOS and watchOS. It lev

Frank Denis 483 Jan 5, 2023
CCCryptor (AES encryption) wrappers for iOS and Mac in Swift. -- For ObjC, see RNCryptor/RNCryptor-objc

RNCryptor Cross-language AES Encryptor/Decryptor data format. The primary targets are Swift and Objective-C, but implementations are available in C, C

null 3.3k Jan 7, 2023
A KeePass/Password Safe Client for iOS and OS X

Strongbox A Personal Password Manager for iOS & OSX that can be found on the Apple App Store here: https://apps.apple.com/app/strongbox-password-safe/

Strongbox 976 Jan 3, 2023
Secretive is an app for storing and managing SSH keys in the Secure Enclave.

Secretive is an app for storing and managing SSH keys in the Secure Enclave.

Max Goedjen 4.9k Jan 1, 2023
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
Easy to use cryptographic framework for data protection: secure messaging with forward secrecy and secure data storage. Has unified APIs across 14 platforms.

Themis provides strong, usable cryptography for busy people General purpose cryptographic library for storage and messaging for iOS (Swift, Obj-C), An

Cossack Labs 1.6k Dec 30, 2022
Cybr/Secure - A simple but powerful secure password generator

A simple but powerful secure password generator. You get the option of password length (10 to 20 characters) and whether you include numbers, symbols, uppercase and/or lowercase letters. Simply tap the lock icon to generate a secure password and then tap to copy the password.

Mykel Agathos 1 Feb 16, 2022
Demonstration of using UIWindowScene and SwiftUI to provide a native-looking Mac preferences window in Catalyst

CatalystPrefsWindow Ever wondered how to create a more Mac-like preferences window for Catalyst? Perhaps Settings Bundles are too limiting for the kin

Steven Troughton-Smith 148 Dec 27, 2022
Demonstration of using Tasks and TaskGroup to thread a calculation.

TasksTest Demonstration of using Tasks and TaskGroup to thread a calculation. The calculation takes place in a separate Swift class that can be reused

null 0 Dec 27, 2021
Demonstration of a Sketching App Using 3D Touch

ForceSketch ####Demonstration of a Sketching App Using 3D Touch #####Companion project to this blog post: http://flexmonkey.blogspot.co.uk/2015/10/for

simon gladman 108 Nov 13, 2022
Demonstration of LegoArtFilter for iOS/macOS

LegoArtFilterDemo Demonstration of LegoArtFilter for iOS/macOS. This project runs on both iOS (14≤) and macOS (11≤). Libraries LegoColors LegoArtFilte

Takuto NAKAMURA (Kyome) 1 Oct 16, 2021
Valorem-demo - Demonstration code and video of Valorem, a bespoke portfolio recommendation platform to be created as an iOS mobile app.

valorem-demo Demonstration code of Valorem, a bespoke portfolio recommendation platform to be created as an iOS mobile app. The included code demonstr

Marcus Deans 1 Mar 4, 2022
Demonstration blackjack app for native iOS. Uses MVVM architecture

Blackjack - native iOS application This project is a simple demonstration on how to intergrate swiftUI with MVVM architecture. Although, technically,

Michael Nguyen 2 Nov 28, 2022