Elegant Swift interface to access the CommonCrypto routines

Overview

SCrypto

Build Status codecov.io Version Carthage Compatible License

[OverviewRequirementsInstallationUsageAlternativesLicence]


Overview

SCrypto provides neat Swift interface to access the CommonCrypto routines.

Features

  • Essential Data and String extensions for message digest, HMAC, PBKDF, symmetric encryption calculation
  • Swift 5.1 support
  • Cocoapods, Carthage and Swift Package Manager compatible
  • Comprehensive Unit Test Coverage
  • Complete Documentation
  • iOS and OS X support

Requirements

  • iOS 9.0+ / macOS 10.11+
  • Swift 3.0+
  • Xcode 8.0+

Installation

Cocoapods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

$ gem install cocoapods

To integrate SCrypto into your Xcode project using CocoaPods, specify it in your Podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios, '9.0'
use_frameworks!

pod 'SCrypto', '~> 2.0.0'

Then, run the following command:

$ pod install

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. You can install Carthage with Homebrew using the following command:

$ brew update
$ brew install carthage

To integrate SCrypto into your Xcode project using Carthage, specify it in your Cartfile:

github "sgl0v/SCrypto" ~> 1.0.0

Run carthage update to build the framework and drag the built SCrypto.framework into your Xcode project.

Swift Package Manager

You can add the SCrypto framework to your project via Swift Package Manager. Add the following line to the dependencies in your Package.swift file:

.package(url: "https://github.com/sgl0v/SCrypto", exact: "<latest version>"),

Finally, include "SCrypto" as a dependency for your executable target:

.target(name: "<target name>", dependencies: ["SCrypto"])

Manually

If you prefer not to use either of the mentioned dependency managers, you can integrate SCrypto into your project manually.

  • Open up Terminal, cd into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:
$ git init
  • Add SCrypto as a git submodule by running the following command:
$ git submodule add https://github.com/sgl0v/SCrypto.git
  • Open the new SCrypto folder, and drag the SCrypto.xcodeproj into the Project Navigator of your application's Xcode project.

    The SCrypto.xcodeproj should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Select the SCrypto.xcodeproj in the Project Navigator and verify the deployment target matches that of your application target.

  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.

  • In the tab bar at the top of that window, open the "General" panel.

  • Click on the + button under the "Embedded Binaries" section.

  • You will see two different SCrypto.xcodeproj folders each with two different versions of the SCrypto.framework iOS nested inside a Products folder.

    It doesn't matter which Products folder you choose from.

  • Just select the SCrypto.framework iOS and that's it!

    The SCrypto.framework is automagically added as a target dependency and should appear as a linked and embedded framework in the Build Phases section.


Usage

Message Digest (MD5, SHA)

Message digests are secure one-way cryptographic hash functions that take arbitrary-sized data and output a fixed-length hash value.

let sha256 = "message".SHA256()

Keyed-hash message authentication code (HMAC)

Hash-based message authentication codes (or HMACs) provides a way for calculating message authentication codes using a cryptographic hash function coupled with a secret key. You can use an HMAC to verify both the integrity and authenticity of a message. The following standard hash algorithm are supported: SHA1, MD5, SHA256, SHA384, SHA512, SHA224.

let secretKey = try! Data.random(32)
let message = "message".data(using: String.Encoding.utf8)!
let hmac = message.hmac(.SHA256, key: secretKey)

Pseudorandom number generator (PRNG)

Generates cryptographically strong random bits suitable for use as cryptographic keys, IVs, nonces etc.

let randomBytes = try! Data.random(16)

Symmetric-key algorithms (AES, DES, TripleDES, CAST, RC2, RC4, Blowfish)

Symmetric-key algorithms use the same cryptographic keys for both encryption of plaintext and decryption of ciphertext. Note that symmetric encryption only provides secrecy but not integrity. There are recent encryption modes which combine symmetric encryption and checked integrity (not supported by CommonCrypto). For this reason it is strongly recommended to combine encryption with a HMAC.

Here is the way to encrypt and decrypt data via AES algorithm in CBC mode with PKCS7 Padding:

let plaintext = "plain text".data(using: String.Encoding.utf8)!
let sharedSecretKey = "shared_secret_key".data(using: String.Encoding.utf8)!.SHA256() // AES-256
let IV = try! Data.random(16) // Randomly generated IV. Length is equal to the AES block size(128)
let ciphertext = try! plaintext.encrypt(.AES, options: .PKCS7Padding, key: sharedSecretKey, iv: IV)
let plaintext2 = try! ciphertext.decrypt(.AES, options: .PKCS7Padding, key: sharedSecretKey, iv: IV)

Password-Based Key Derivation Function (PBKDF2)

Key derivation functions are used for turning a passphrase into an arbitrary length key for use as a cryptographic key in subsequent operations.

let password = "password".data(using: String.Encoding.utf8)!
let salt = try! Data.random(32)
let derivedKey = try! password.derivedKey(salt, pseudoRandomAlgorithm: .SHA256, rounds: 20, derivedKeyLength: 32)

Alternatives

Looking for something else? Try another Swift CommonCrypto wrappers:


Licence

SCrypto is MIT-licensed. See LICENSE.

You might also like...
Virgil Crypto stack Objective-C/Swift

Virgil Crypto Library Objective-C/Swift Introduction | Library purposes | Installation | Usage examples | Docs | License | Contacts Introduction Virgi

A framework for the JOSE standards JWS, JWE, and JWK written in Swift.

JOSESwift is a modular and extensible framework for the JOSE standards JWS, JWE, and JWK written in Swift. 💡 Please note that this implementation of

Elegant Swift interface to access the CommonCrypto routines

SCrypto [Overview • Requirements • Installation • Usage • Alternatives • Licence] Overview SCrypto provides neat Swift interface to access the CommonC

Elegant Swift interface to access the CommonCrypto routines

SCrypto [Overview • Requirements • Installation • Usage • Alternatives • Licence] Overview SCrypto provides neat Swift interface to access the CommonC

A stand-alone Swift wrapper around the FileMaker XML Web publishing interface, enabling access to FileMaker servers.
A stand-alone Swift wrapper around the FileMaker XML Web publishing interface, enabling access to FileMaker servers.

Perfect - FileMaker Server Connector This project provides access to FileMaker Server databases using the XML Web publishing interface. This package b

Swift cross-platform crypto library using CommonCrypto/libcrypto

BlueCryptor Swift cross-platform crypto library derived from IDZSwiftCommonCrypto. IMPORTANT NOTE: This release is NOT entirely source code compatible

Swift cross-platform crypto library using CommonCrypto/libcrypto

BlueCryptor Swift cross-platform crypto library derived from IDZSwiftCommonCrypto. IMPORTANT NOTE: This release is NOT entirely source code compatible

Read my answer here Importing CommonCrypto in a Swift framework

Read my answer here Importing CommonCrypto in a Swift framework

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

Swift framework wrapping CommonCrypto's SHA256 methods.

SHA256-Swift Swift framework wrapping CommonCrypto's SHA256 methods. This is experimental. Do not use this in a production system. Installation instru

Uncomplicated cryptography frameworks base on CommonCrypto

Keys - Keys of data encryption 中文介绍 Example let password = Password("Secret") let key = SymmetricKey() password.encrypt(data) let data = "Hello Wo

Elegant ⏱ interface for Swift apps

Each Elegant ⏱ interface for Swift apps Each is a NSTimer bridge library written in Swift. Features Requirements Installation Usage Leaks License Feat

AEOTPTextField - A beautiful iOS OTP Text Field library, written in Swift with full access customization in UI.
AEOTPTextField - A beautiful iOS OTP Text Field library, written in Swift with full access customization in UI.

AEOTPTextField - A beautiful iOS OTP Text Field library, written in Swift with full access customization in UI.

A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.
A stand-alone Swift wrapper around the mongo-c client library, enabling access to MongoDB servers.

This package is deprecated in favour of the official Mongo Swift Driver. We advise users to switch to that pack

Perfect - a Swift wrapper around the MySQL client library, enabling access to MySQL database servers.
Perfect - a Swift wrapper around the MySQL client library, enabling access to MySQL database servers.

Perfect - MySQL Connector This project provides a Swift wrapper around the MySQL client library, enabling access to MySQL database servers. This packa

A stand-alone Swift wrapper around the libpq client library, enabling access to PostgreSQL servers.
A stand-alone Swift wrapper around the libpq client library, enabling access to PostgreSQL servers.

Perfect - PostgreSQL Connector This project provides a Swift wrapper around the libpq client library, enabling access to PostgreSQL servers. This pack

Declarative Swift framework for Attributed Role-based Access Control management
Declarative Swift framework for Attributed Role-based Access Control management

Koosa Declarative Swift framework for Attributed Role-based Access Control management Check out this blog post for full explanation and more details:

Access Xcode Server API with native Swift objects.

Xcode Server SDK Use Xcode Server's API with native Swift objects. First brought to you in Buildasaur, now in an independent project. This is an unoff

A stand-alone Swift wrapper around the MySQL client library, enabling access to MySQL servers.
A stand-alone Swift wrapper around the MySQL client library, enabling access to MySQL servers.

Perfect - MySQL Connector This project provides a Swift wrapper around the MySQL client library, enabling access to MySQL database servers. This packa

Comments
  • iOS 11 error message: Could not build Objective-C module 'CommonCrypto'

    iOS 11 error message: Could not build Objective-C module 'CommonCrypto'

    It looks like my module.map is pointing to iOS 10.3 SDK, which is not found:

    module CommonCrypto [system] {
    	header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    	header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneOS.platform/Developer/SDKs/iPhoneOS10.3.sdk/usr/include/CommonCrypto/CommonRandom.h"
    	export *
    	}
    
    opened by alijaza 9
  • i get some warnings on build

    i get some warnings on build

    hi, how can i resolve this problems?

    mahdipishguy@mahdis-Mac Runner % flutter run       
    Changing current working directory to: /Users/mahdipishguy/Documents/projects/unlimited_power_pro
    Launching lib/main.dart on iPhone 8 in debug mode...
     
    Running Xcode build...                                                  
                                                       
    Xcode build done.                                           24.3s
    Failed to build iOS app
    Error output from Xcode build:
    ↳
        ** BUILD FAILED **
    
    
    Xcode's output:
    ↳
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:107:111: error: using '!' is not allowed here; perhaps '?' was intended?
                typealias Function = (_ data: UnsafeRawPointer, _ len: CC_LONG, _ md: UnsafeMutablePointer<UInt8>) -> UnsafeMutablePointer<UInt8>!
                                                                                                                      ^                          ~
                                                                                                                                                 ?
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:188:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func MD2() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:198:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func MD4() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:208:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func MD5() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:217:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func SHA1() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:226:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func SHA224() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:235:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func SHA256() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:244:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func SHA384() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:253:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func SHA512() -> Self {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:330:5: warning: 'public' modifier is redundant for static method declared in a public extension
            public static func random(_ length : Int) throws -> Data {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:432:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func hmac(_ algorithm: HMAC.Algorithm, key: Data) -> Data {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:453:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func hmac(_ algorithm: HMAC.Algorithm, key: String) -> String {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:628:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func encrypt(_ algorithm: Cipher.Algorithm, options: Cipher.Options, key: Data, iv: Data? = nil) throws -> Data {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:646:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func decrypt(_ algorithm: Cipher.Algorithm, options: Cipher.Options, key: Data, iv: Data? = nil) throws -> Data {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:745:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func derivedKey(_ salt: Data, pseudoRandomAlgorithm: PBKDF.PseudoRandomAlgorithm, rounds: UInt32, derivedKeyLength: Int) throws -> Data {
            ^~~~~~~
    
        /Users/mahdipishguy/Documents/projects/unlimited_power_pro/ios/Pods/SCrypto/Source/SCrypto.swift:760:5: warning: 'public' modifier is redundant for instance method declared in a public extension
            public func calibrate(_ saltLength: Int, pseudoRandomAlgorithm: PBKDF.PseudoRandomAlgorithm, derivedKeyLength: Int, msec : UInt32) -> UInt {
            ^~~~~~~
    
        note: Using new build system
        note: Planning build
        note: Constructing build description
    
    Could not build the application for the simulator.
    Error launching application on iPhone 8.
    mahdipishguy@mahdis-Mac Runner % 
    
    opened by pishguy 2
  • Swift 4.1 support

    Swift 4.1 support

    Hi! thanks for this library you saved my life :)

    can you update it to support Swift 4.1 to remove just one warning? (change "!" for "?" in one line of code)

    and also can you update please the cocoapods file to use that update with cocoapods :)

    thanks!!

    opened by xZeok 1
  • iOS 11 error message: Could not build Objective-C module 'CommonCrypto'

    iOS 11 error message: Could not build Objective-C module 'CommonCrypto'

    my module map:

    module CommonCrypto [system] {
    	header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    	header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator11.0.sdk/usr/include/CommonCrypto/CommonRandom.h"
    	export *
    	}
    

    removing pods folder and performing install does nothing

    opened by rredpoppy 1
Releases(4.0.1)
Owner
Max
Lead Software Engineer | iOS | Android
Max
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
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
A pure Swift implementation of MD5

SwiftMD5 SwiftMD5 is a pure Swift implementation for the MD5 algorithm. Usage import SwiftMD5 "The quick brown fox jumps over the lazy dog".md5 // "9

Matthew Purland 11 Sep 25, 2021
🍕 MD5 in pure Swift

SwiftHash ❤️ Support my app ❤️ Push Hero - pure Swift native macOS application to test push notifications Quick Access - Organise files in the Mac men

Khoa 207 Dec 24, 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
RSA public/private key encryption in Swift

SwiftyRSA Maintainer(s): @ikeith Public key RSA encryption in Swift. SwiftyRSA is used in the Scoop iOS app to encrypt driver license numbers before s

Scoop 1.1k Jan 5, 2023
Enigma encryption in Swift

?????????????????? ?????????? // Will create an Enigma with an empty plugboard, rotors I, II, III and reflector B (wide). let enigma = Enigma() // Wil

Joakim Gyllström 113 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
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