• Stars
    star
    189
  • Rank 197,474 (Top 5 %)
  • Language
    Swift
  • License
    Apache License 2.0
  • Created about 8 years ago
  • Updated about 2 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Swift cross-platform crypto library using CommonCrypto/libcrypto

APIDoc Build Status - Master macOS iOS Linux Apache 2 Slack Status

BlueCryptor

Swift cross-platform crypto library derived from IDZSwiftCommonCrypto.

IMPORTANT NOTE: This release is NOT entirely source code compatible with previous releases. There are instances where exceptions are thrown now instead of the framework calling fatalError(). This means that there are more recoverable errors in the library than before. The only time that fatalError() is called is to indicate either a programming error or a non-recoverable system error.

Note: On macOS and iOS, BlueCryptor uses the Apple provided CommonCrypto library. On Linux, it uses libcrypto from the OpenSSL project.

Prerequisites

Swift

  • Swift Open Source swift-5.1-RELEASE toolchain (Minimum REQUIRED for latest release)
  • Swift Open Source swift-5.4-RELEASE toolchain (Recommended)
  • Swift toolchain included in Xcode Version 11.0 or higher.

macOS

  • macOS 10.14.6 (Mojave) or higher.
  • Xcode Version 11.0 or higher using one of the above toolchains.
  • Xcode Version 12.5 or higher using the included toolchain (Recommended).
  • CommonCrypto is provided by macOS.

iOS

  • iOS 10.0 or higher
  • Xcode Version 11.0 or higher using one of the above toolchains.
  • Xcode Version 12.5 or higher using the included toolchain (Recommended).
  • CommonCrypto is provided by iOS.

Linux

  • Ubuntu 16.04 (or 16.10 but only tested on 16.04) and 18.04.
  • One of the Swift Open Source toolchain listed above.
  • OpenSSL is provided by the distribution. Note: 1.0.x, 1.1.x and later releases of OpenSSL are supported.
  • The appropriate libssl-dev package is required to be installed when building.

Build

To build Cryptor from the command line:

% cd <path-to-clone>
% swift build

Testing

To run the supplied unit tests for Cryptor from the command line:

% cd <path-to-clone>
% swift build
% swift test

Getting started

Including in your project

Swift Package Manager

To include BlueCryptor into a Swift Package Manager package, add it to the dependencies attribute defined in your Package.swift file. You can select the version using the majorVersion and minor parameters. For example:

	dependencies: [
		.Package(url: "https://github.com/Kitura/BlueCryptor.git", majorVersion: <majorVersion>, minor: <minor>)
	]

Carthage

To include BlueCryptor in a project using Carthage, add a line to your Cartfile with the GitHub organization and project names and version. For example:

	github "Kitura/BlueCryptor" ~> <majorVersion>.<minor>

CocoaPods

To include BlueCryptor in a project using CocoaPods, you just add BlueCryptor to your Podfile, for example:

    platform :ios, '10.0'

    target 'MyApp' do
        use_frameworks!
        pod 'BlueCryptor'
    end

Before starting

The first thing you need to do is import the Cryptor framework. This is done by the following:

import Cryptor

API

Cryptor

The following code demonstrates encryption and decryption using AES single block CBC mode using optional chaining.

let key = CryptoUtils.byteArray(fromHex: "2b7e151628aed2a6abf7158809cf4f3c")
let iv = CryptoUtils.byteArray(fromHex: "00000000000000000000000000000000")
let plainText = CryptoUtils.byteArray(fromHex: "6bc1bee22e409f96e93d7e117393172a")

var textToCipher = plainText
if plainText.count % Cryptor.Algorithm.aes.blockSize != 0 {
	textToCipher = CryptoUtils.zeroPad(byteArray: plainText, blockSize: Cryptor.Algorithm.aes.blockSize)
}
do {
	let cipherText = try Cryptor(operation: .encrypt, algorithm: .aes, options: .none, key: key, iv: iv).update(byteArray: textToCipher)?.final()
		
	print(CryptoUtils.hexString(from: cipherText!))
		
	let decryptedText = try Cryptor(operation: .decrypt, algorithm: .aes, options: .none, key: key, iv: iv).update(byteArray: cipherText!)?.final()

	print(CryptoUtils.hexString(from: decryptedText!))
} catch let error {
	guard let err = error as? CryptorError else {
		// Handle non-Cryptor error...
		return
	}
	// Handle Cryptor error... (See Status.swift for types of errors thrown)
}

Digest

The following example illustrates generating an MD5 digest from both a String and an instance of NSData.

let qbfBytes : [UInt8] = [0x54,0x68,0x65,0x20,0x71,0x75,0x69,0x63,0x6b,0x20,0x62,0x72,0x6f,0x77,0x6e,0x20,0x66,0x6f,0x78,0x20,0x6a,0x75,0x6d,0x70,0x73,0x20,0x6f,0x76,0x65,0x72,0x20,0x74,0x68,0x65,0x20,0x6c,0x61,0x7a,0x79,0x20,0x64,0x6f,0x67,0x2e]
let qbfString = "The quick brown fox jumps over the lazy dog."

// String...
let md5 = Digest(using: .md5)
md5.update(string: qfbString)
let digest = md5.final()

// NSData using optional chaining...
let qbfData = CryptoUtils.data(from: qbfBytes)
let digest = Digest(using: .md5).update(data: qbfData)?.final()

HMAC

The following demonstrates generating an SHA256 HMAC using byte arrays for keys and data.

let myKeyData = "0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b0b"
let myData = "4869205468657265"
let key = CryptoUtils.byteArray(fromHex: myKeyData)
let data : [UInt8] = CryptoUtils.byteArray(fromHex: myData)

let hmac = HMAC(using: HMAC.Algorithm.sha256, key: key).update(byteArray: data)?.final()

Key Derivation

The following illustrates generating a key using a password, salt, number of rounds and a specified derived key length using the SHA1 algorithm. Then it shows how to generate a String from resultant key.

let password = "password"
let salt = salt
let rounds: UInt = 2
let derivedKeyLen = 20
do {
	let key = PBKDF.deriveKey(fromPassword: password, salt: salt, prf: .sha1, rounds: rounds, derivedKeyLength: derivedKeyLen)
	let keyString = CryptoUtils.hexString(from: key)
} catch let error {
	guard let err = error as? CryptorError else {
		// Handle non-Cryptor error...
		return
	}
	// Handle Cryptor error... (See Status.swift for types of errors thrown)
}

Random Byte Generation

The following demonstrates generating random bytes of a given length.

let numberOfBytes = 256*256
do {
	let randomBytes = try Random.generate(byteCount: numberOfBytes)
} catch {
  	print("Error generating random bytes")
}

Utilities

Cryptor also provides a set of data manipulation utility functions for conversion of data from various formats:

  • To byteArray ([UInt8])
    • From hex string
    • From UTF8 string
  • To Data
    • From hex string
    • From byte array ([UInt8])
  • To NSData
    • From hex string
    • From byte array ([UInt8])
  • To NSString
    • From byte array ([UInt8])
  • To hexList (String)
    • From byte array ([UInt8])

Also provided are an API to pad a byte array ([UInt8]) such that it is an integral number of block size in bytes long.

  • func zeroPad(byteArray: [UInt8], blockSize: Int) -> [UInt8]
  • func zeroPad(string: String, blockSize: Int) -> [UInt8]

Restrictions

The following algorithm is not available on Linux since it is not supported by OpenSSL.

  • Digest: MD2

In all cases, use of unsupported APIs or algorithms will result in a Swift fatalError(), terminating the program and should be treated as a programming error.

Community

We love to talk server-side Swift and Kitura. Join our Slack to meet the team!

License

This library is licensed under Apache 2.0. Full license text is available in LICENSE.

More Repositories

1

Kitura

A Swift web framework and HTTP server.
Swift
7,614
star
2

BlueSocket

Socket framework for Swift using the Swift Package Manager. Works on iOS, macOS, and Linux.
Swift
1,392
star
3

Swift-JWT

JSON Web Tokens in Swift
Swift
539
star
4

Swift-Kuery

SQL database abstraction layer
Swift
427
star
5

Swift-SMTP

Swift SMTP client
Swift
249
star
6

Swift-Kuery-ORM

An ORM for Swift, built on Codable
Swift
211
star
7

HeliumLogger

A lightweight logging framework for Swift
Swift
175
star
8

swift-html-entities

HTML5 spec-compliant character encoder/decoder for Swift
Swift
165
star
9

swift-ubuntu-docker

🚫 This repo is deprecated - please use the images here: https://hub.docker.com/_/swift
Vim Script
155
star
10

BlueRSA

RSA public/private key encryption, private key signing and public key verification in Swift using the Swift Package Manager. Works on iOS, macOS, and Linux (work in progress).
Swift
128
star
11

SwiftyRequest

SwiftyRequest is an HTTP networking library built for Swift.
Swift
108
star
12

Kitura-net

Kitura networking
Swift
103
star
13

BlueSSLService

SSL/TLS Add-in for BlueSocket using Secure Transport and OpenSSL
Swift
96
star
14

Kitura-redis

Swift Redis library
Swift
94
star
15

BlueECC

Elliptic-curve cryptography for Swift
Swift
92
star
16

BlueSignals

Generic Cross Platform Signal Handler
Swift
92
star
17

Kitura-Sample

A sample application that shows how to use various features of Kitura
Swift
80
star
18

Configuration

Hierarchical configuration manager for Swift applications
Swift
78
star
19

Kitura-WebSocket

WebSocket support for Kitura
Swift
66
star
20

Swift-Kuery-PostgreSQL

PostgreSQL plugin for Swift-Kuery framework
Swift
61
star
21

OpenSSL

Swift modulemaps for libSSL and libcrypto
C
58
star
22

SwiftKafka

Swift SDK for Apache Kafka
Swift
58
star
23

KituraKit

Swift client library for using Codable routes with Kitura
Swift
58
star
24

Kitura-CouchDB

CouchDB adapter for Kitura
Swift
50
star
25

CircuitBreaker

A Swift Circuit Breaker library – Improves application stability and reliability.
Swift
45
star
26

Kitura-Credentials

A pluggable framework for validating user credentials in a Swift server using Kitura
Swift
40
star
27

Kitura-NIO

A networking library for Kitura, based on SwiftNIO
Swift
37
star
28

Kitura-OpenAPI

OpenAPI support for Kitura
Swift
36
star
29

TypeDecoder

A Swift library to allow the runtime inspection of Swift language native and complex types.
Swift
35
star
30

SwiftKueryMySQL

MySQL plugin for Swift-Kuery framework
Swift
34
star
31

Package-Builder

Build and utility scripts used for continuous integration builds for Swift Package Manager projects on the Travis CI environment
Shell
33
star
32

CCurl

Modulemap for the libcurl library
Objective-C
30
star
33

Kitura-StencilTemplateEngine

Stencil templating for Kitura
Swift
26
star
34

kitura.dev

http://www.kitura.dev
JavaScript
26
star
35

LoggerAPI

Logger protocol
Swift
25
star
36

Kitura-Markdown

Templating engine for Kitura that uses Markdown based templates
C
24
star
37

Health

An application health library for Swift.
Swift
21
star
38

Kitura-Session

A pluggable framework for managing user sessions in a Swift server using Kitura
Swift
18
star
39

Kitura-WebSocket-NIO

A SwiftNIO based implementation of WebSocket for Kitura
Swift
17
star
40

CommonCrypto

CommonCrypto Module Map
Swift
17
star
41

FileKit

Swift
16
star
42

Swift-Kuery-SQLite

An SQLite plugin for the Swift-Kuery framework
Swift
16
star
43

Kitura-TemplateEngine

Kitura Template Engine protocol
Swift
15
star
44

Kitura-CredentialsHTTP

A plugin for the Kitura-Credentials framework that authenticates using HTTP Basic and Digest authentication
Swift
15
star
45

kitura-cli

⌨️ Kitura command-line interface
Go
13
star
46

KituraContracts

A library containing type definitions shared by client and server Kitura code.
Swift
12
star
47

CZlib

Module map for Zlib library
Swift
11
star
48

CloudEnvironment

Convenience Swift package for accessing environment variables, credentials.
Swift
11
star
49

Kitura-CredentialsFacebook

A plugin for the Kitura-Credentials framework that authenticates using the Facebook web login
Swift
9
star
50

Kitura-CORS

Kitura CORS middleware
Swift
9
star
51

Kitura-Cache

Kitura cache
Swift
9
star
52

Kitura-CredentialsGoogle

A plugin for the Kitura-Credentials framework that authenticates using the Google web login
Swift
8
star
53

Swift-cfenv

Easy access to Cloud Foundry application environment for Swift Packages.
Swift
8
star
54

Kitura-Compression

Kitura compression middleware
Swift
6
star
55

CEpoll

A modulemap file and include to help Swift code use epoll on Linux
Swift
5
star
56

Kitura-WebSocket-Client

A WebSocket client based on SwiftNIO
Swift
5
star
57

Kitura-CredentialsGitHub

A plugin for the Kitura-Credentials framework that authenticates using the GitHub web login
Swift
4
star
58

Kitura-MustacheTemplateEngine

Adapter of GRMustache Template Engine to Kitura Template Engine
Swift
4
star
59

CHTTPParser

Modulemap for the http-parser library
C
4
star
60

Kitura-WebSocket-Compression

A WebSocket compression library based on SwiftNIO
Swift
3
star
61

Kitura-Session-Redis

Kitura-Session store using Redis as the backing store
Swift
3
star
62

generator-swiftserver-projects

Autogenerated Kitura projects
Shell
2
star
63

Kitura-CredentialsJWT

A plugin for the Kitura-Credentials framework that supports JWT authentication.
Swift
2
star
64

homebrew-kitura

Homebrew tap
Ruby
2
star
65

Kitura-Benchmarks

Benchmarks for Kitura
Swift
2
star
66

anapistula

Simple standalone web server in swift
Swift
1
star
67

CLibpq

PostgreSQL wrapper
Swift
1
star
68

ShellToolKit

Utility classes to help with common system/shell actions in Swift
Swift
1
star