Uncomplicated cryptography frameworks base on CommonCrypto

Overview

Carthage compatible Version License

Keys - Keys of data encryption

中文介绍

Example

	let password = Password("Secret")
	let key = SymmetricKey()
	password.encrypt(data)
	let data = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)!
	let encryptedData = key.encrypt(data)
	let decryptedData = key.decrypt(encryptedData)
	print(decryptedData) // "Hello World!"

Keys is a data encryption framework for iOS / OS X. It's simplifies the most difficult parts of CommonCrypto, so you don't have to deal with those head stretching interfaces on your own.

Keys is design to work with Best practice encryption only. If you are not familiar with Master Key encryption and Public Key cncryption, Please read the following materials to learn about how iMessage and 1Password protect your data.

Three type of Keys

There're three kind of keys in the framwork. Use them according to what you are encrypting.

  • Symmetric Key for encrypting / decrypting local data saving in the same device
  • Asymmetric Keys for encrypting / decrypting data need to be transfers between devices or servers.
  • Password for encrypting / decrypting Symmetric Keys

Best practice

Carthage

Please intall Carthage then insert the following code into your Cartfile.

	github "remaerd/Keys"

Encrypting local data

When you need to encrypt a piece of data. You need to create a SymmetricKey object to encrypt the data. Then, create a Password object from users' String password. Finally, encrypt the SymmetricKey object with the Password. Encrypting your users's data with String password is consider dangerous and naïve, please never do this. Again, You must NOT encrypt data with users' String password.

Creating Password object

	let password = Password("Hello")
	let salt = password.salt
	let rounds = password.rounds
	let data = password.data

When you create a new Password object with String. A random salt and rounds number will be generated with it. You need to save the salt and rounds data locally, or you will create different Password object with the same String.

Do NOT save the password.data locally, or hackers will decrypt users' data by decrypting other encryption keys without the password.

Creating SymmetricKey object

	let key = SymmetricKey()
	let encryptionKey = key.cryptoKey
	let iv = key.IV
	let hmacKey = key.hmacKey

When you are encrypting local data. You will need a SymmetricKey object to encrypt your data. Random Data will be generate safely, and you need to save the cryptoKey, IV and hmacKey of a SymmetricKey if you need to use the same SymmetricKey later.

Encrypting data

	let key = SymmetricKey()
	let data = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)!
	do {
		let encryptedData = try key.encrypt(data)
		print(encryptedData)
	} catch {
		print("Cannot encrypt data")
	}

Decrypting data

	let key = SymmetricKey(key: keyData, hmacKey: hmacData, IV: IVData)
	do {
		let decryptedData = try key.decrypt(data)
		print(decryptedData)
	} catch {
		print("Cannot decrypt data")
	}

Encrypting data between devices / servers

When you need to encrypt data between devices, 'AsymmetricKeys' is the only option. Imagine there're two keys for one safe. You open a safe with a key and put gold into it. And you give a different key to someone you trust, then he can open the safe with a different key, but he can't put gold into your safe.

Creating AsymmetricKeys object

	let keys = AsymmetricKeys.generateKeyPair()
	let publicKey = keys.publicKey
	let privateKey = key.privateKey

When your create a pair of AsymmetricKeys, a publicKey and a privateKey will be generated. So you can use them to encrypt data, then send the other key and encrypted data to third-parties.

It's a good practice to generate two pair of AsymmetricKeys, so you can encrypt / decrypt / sign / validate your data with these four keys.

CommonCrypto vs. OpenSSL

If you use AsymmetricKeys.generateKeyPair() to generate AsymmetricKeys. those keys only works between iOS devices. If you need to use those keys between servers or Android devices. you need to use OpenSSL to create RSA Asymmetric Keys.

To encrypt iOS devices' data, do this:

	let data = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)!
	let keys = AsymmetricKeys.generateKeyPair()
	let publicKey = keys.publicKey
	let privateKey = keys.privateKey
	do {
		let encryptedData = try privateKey.encrypt(data)
		let decryptedData = try publicKey.decrypt(data)
		print(NSString(data: decryptedData, encoding: NSUTF8StringEncoding))
		// Hello World
	} catch {
		print("Cannot encrypt data")
	}

If you need to transfer encrypted between iOS Device and your servers. Generate RSA keys like this with the terminal.app

	openssl genrsa -out private.pem 2048
	openssl rsa -in private.pem -pubout -out public.pub 

The iOS client get the Public Key and encrypted data. So you can decrypt the data with the public key.

	let data = "Hello World!".dataUsingEncoding(NSUTF8StringEncoding)!
	let publicKeyData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("keys-public", withExtension: "pem")!)!
  let privateKeyData = NSData(contentsOfURL: NSBundle.mainBundle().URLForResource("keys-private", withExtension: "pem")!)!
	do {
		let publicKey = try PublicKey(publicKey:privateKeyData)
		let privateKey = try PrivateKey(privateKey:privateKeyData)
		let encryptedData = try privateKey.encrypt(data)
		let decryptedData = try publicKey.decrypt(encryptedData)
		print(NSString(data: decryptedData, encoding: NSUTF8StringEncoding))
		// Hello World
	} catch {
		print("Cannot decrypt data")
	}
You might also like...
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

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

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

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

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

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

Spin aims to provide a versatile Feedback Loop implementation working with the three main reactive frameworks available in the Swift community (RxSwift, ReactiveSwift and Combine)
Spin aims to provide a versatile Feedback Loop implementation working with the three main reactive frameworks available in the Swift community (RxSwift, ReactiveSwift and Combine)

With the introduction of Combine and SwiftUI, we will face some transition periods in our code base. Our applications will use both Combine and a thir

 Reactive extensions to Cocoa frameworks, built on top of ReactiveSwift.
Reactive extensions to Cocoa frameworks, built on top of ReactiveSwift.

ReactiveSwift offers composable, declarative and flexible primitives that are built around the grand concept of streams of values over time. These primitives can be used to uniformly represent common Cocoa and generic programming patterns that are fundamentally an act of observation.

A Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and other native frameworks.
A Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and other native frameworks.

ZamzamKit ZamzamKit is a Swift package for rapid development using a collection of micro utility extensions for Standard Library, Foundation, and othe

Paginated endless scroll using the SwiftUI and Combine frameworks
Paginated endless scroll using the SwiftUI and Combine frameworks

Article related to this project Infinite List Scroll with SwiftUI and Combine. InfiniteListSwiftUI A sample project showcasing how to build an infinit

macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support
macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support

xcframework-maker macOS utility for converting fat-frameworks to SPM-compatible XCFramework with arm64-simulator support. 📝 Description make-xcframew

This repository contains a detailed sample app that implements VIPER architecture in iOS using libraries and frameworks like Alamofire, AlamofireImage, PKHUD, CoreData etc.
This repository contains a detailed sample app that implements VIPER architecture in iOS using libraries and frameworks like Alamofire, AlamofireImage, PKHUD, CoreData etc.

iOS Viper Architecture: Sample App This repository contains a detailed sample app that implements VIPER architecture using libraries and frameworks li

Apple's iOS Private Frameworks
Apple's iOS Private Frameworks

iOS Private Framework This repo contains reversed-engendered private frameworks used by Apple in iOS. Private frameworks are frameworks which you are

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer documentation.

Swift-DocC is a documentation compiler for Swift frameworks and packages aimed at making it easy to write and publish great developer docum

Easy to use SMJobBless, along with a full Swift implementation of the Authorization Services and Service Management frameworks

Leverage SMJobBless functionality with just one function call: let message = "Example App needs your permission to do thingamajig." let icon = Bundle.

Swift JSExport extensions for macOS system frameworks
Swift JSExport extensions for macOS system frameworks

framework-bridge Swift JSExport extensions for macOS system frameworks. Progress Foundation AppKit Usage Swift import JavaScriptCore import FrameworkB

iOS application to extract accession numbers from wall labels using Vision and VisionKit frameworks.
iOS application to extract accession numbers from wall labels using Vision and VisionKit frameworks.

iOS application to extract accession numbers from wall labels using Vision and VisionKit frameworks. Important This is experimenta

SkyWite is an open-source and highly versatile multi-purpose frameworks.

SkyWite is an open-source and highly versatile multi-purpose frameworks. Clean code and sleek features make SkyWite an ideal choice. Powerful high-level networking abstractions built into Cocoa. It has a modular architecture with well-designed, feature-rich APIs that are a joy to use.

Releases(v1.0)
Owner
Xingzhi Zheng
Designer, Developer & Lecturer of Graphics, Apps & Games.
Xingzhi Zheng
Swift HybridCrypto is simple customizable implementation of hybrid cryptography (AES+RSA+Hash) recommended by OWASP.

HybridCrypto (Swift) HybridCrypto is simple implementation of hybrid cryptography following recommendations by OWASP. Prerequisites: Minimum iOS SDK:

UTNGY Pisal 2 Sep 6, 2022
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

Kitura 183 Oct 15, 2022
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

Max 39 Mar 31, 2022
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

Kitura 183 Oct 15, 2022
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

Max 35 Feb 15, 2021
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

Cryptocoin for Swift 70 Dec 26, 2022
Apple's iOS Private Frameworks

iOS Private Framework This repo contains reversed-engendered private frameworks used by Apple in iOS. Private frameworks are frameworks which you are

Reels Research, Inc. 8 Oct 25, 2022
Wrapper class for handling all tasks related to RSA cryptography

RSAWrapper Wrapper class for handling all tasks related to RSA cryptography USAG

null 1 Dec 24, 2021
Swift HybridCrypto is simple customizable implementation of hybrid cryptography (AES+RSA+Hash) recommended by OWASP.

HybridCrypto (Swift) HybridCrypto is simple implementation of hybrid cryptography following recommendations by OWASP. Prerequisites: Minimum iOS SDK:

UTNGY Pisal 2 Sep 6, 2022
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

Kitura 183 Oct 15, 2022