Using Themis with Swift (iOS/OSX)

Introduction

The objc-themis wrapper provides access to the features and functions of the Themis cryptographic library:

  • Key generation: the creation of public/private key pairs, used in Secure Message and Secure Session.
  • Secure Message: the secure exchange of messages between two parties. RSA + PSS + PKCS#7 or ECC + ECDSA (based on key choice), AES GCM container.
  • Secure Storage (aka Secure Cell): provides secure storage of record based data through symmetric encryption and data authentication. AES GCM / AES CTR containers.
  • Secure Session: the establishment of a session between two peers, within which the data can be securely exchanged with higher security guarantees. EC + ECDH, AES container.

Now using Themis in Swift is easy!

Quickstart

Building Themis

Requirements

In addition to the common set of build tools, Themis currently uses OpenSSL under the hood. It is already included in CocoaPods dependencies so you don't have to worry about that!

Installing Themis

Themis for iOS/OSX uses CocoaPods dependency manager.

Add the following lines to your .podfile:

source 'https://github.com/CocoaPods/Specs.git'
platform :ios
pod 'themis'

Using Secure Comparator

If you want to use Secure Comparator, you should enable it passing compiler flag. It's easy to do by adding the following lines to your Podfile:

post_install do |installer_representation|
    installer_representation.pods_project.targets.each do |target|
        target.build_configurations.each do |config|
            config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] ||= ['$(inherited)']
            config.build_settings['GCC_PREPROCESSOR_DEFINITIONS'] << 'SECURE_COMPARATOR_ENABLED'
        end
    end
end

And add this to the Bridging Header file:

#define SECURE_COMPARATOR_ENABLED
#import <objcthemis/scomparator.h>
Using BoringSSL

By default Themis uses OpenSSL as crypto-engine. If your project uses BoringSSL or GRPC libraries, you might want to switch to BoringSSL crypto-engine for Themis as well (available since 0.10.1):

pod 'themis/themis-boringssl'

Examples

Using Themis

Bridging Header

Please add #import <objcthemis/objcthemis.h> into your project's Bridging Headers (something that looks like ProjectName-Bridging-Header.h). Now you can use Themis from any Swift file! (How to create a Bridging Header file?)

Keypair generation

Private/public keypair generation

Themis supports both Elliptic Curve and RSA algorithms for asymmetric cryptography. Algorithm type is chosen according to the generated key type. Asymmetric keys are needed for Secure Message and Secure Session objects.

WARNING: When you distribute private keys to your users, make sure the keys are sufficiently protected. You can find the guidelines here.

Note: When using public keys of other peers, make sure they come from trusted sources.

Keypair generation interface

To generate a pair of keys, objcthemis has a class TSKeyGen. Method init has one parameter - the algorithm type (Elliptic Curve (EC) or RSA algorithms).

/* .EC or .RSA can be used*/
guard let keyGeneratorRSA: TSKeyGen = TSKeyGen(algorithm: .RSA) else {
    print("Error occured while initialising object keyGeneratorRSA", #function)
    return
}
let privateKeyRSA: Data = keyGeneratorRSA.privateKey as Data
let publicKeyRSA: Data = keyGeneratorRSA.publicKey as Data

Secure Message

The Secure Message functions provide a sequence-independent, stateless, contextless messaging system. This may be preferred in cases that don't require frequent sequential message exchange and/or in low-bandwidth contexts. This is secure enough to exchange messages from time to time, but if you'd like to have Perfect Forward Secrecy and higher security guarantees, please consider using Secure Session instead.

The Secure Message functions offer two modes of operation:

In Sign/Verify mode, the message is signed using the sender's private key and is verified by the receiver using the sender's public key. The message is packed in a suitable container and ECDSA is used by default to sign the message (when RSA key is used, RSA+PSS+PKCS#7 digital signature is used).

In Encrypt/Decrypt mode, the message will be encrypted with a randomly generated key (in RSA) or a key derived by ECDH (in ECDSA), via symmetric algorithm with Secure Cell in seal mode (keys are 256 bits long).

Read more about Secure Message's cryptographic internals here.

Encryption

To encrypt a message, use client private key and server public key, and convert them to NSData:

// base64 encoded keys
let serverPublicKeyString: String = "VUVDMgAAAC2ELbj5Aue5xjiJWW3P2KNrBX+HkaeJAb+Z4MrK0cWZlAfpBUql"
let clientPrivateKeyString: String = "UkVDMgAAAC13PCVZAKOczZXUpvkhsC+xvwWnv3CLmlG0Wzy8ZBMnT+2yx/dg"

guard let serverPublicKey: Data = Data(base64Encoded: serverPublicKeyString,
                                           options: .ignoreUnknownCharacters),
    let clientPrivateKey: Data = Data(base64Encoded: clientPrivateKeyString,
                                          options: .ignoreUnknownCharacters) else {
    print("Error occurred during base64 encoding", #function)
    return
}

Initialise encrypter:

let encrypter: TSMessage = TSMessage.init(inEncryptModeWithPrivateKey: clientPrivateKey,
                                                  peerPublicKey: serverPublicKey)!

Encrypt message:

let message: String = "- Knock, knock.\n- Who’s there?\n*very long pause...*\n- Java."

var encryptedMessage: Data = Data()
do {
    encryptedMessage = try encrypter.wrap(message.data(using: .utf8))
    print("encryptedMessage = \(encryptedMessage)")

} catch let error as NSError {
    print("Error occurred while encrypting \(error)", #function)
    return
}

Result (the encryption result for the same data chunk is different every time and can't be used as a test):

$ <20270426 53000000 00010140 0c000000 10000000 1f000000 ad443c21 d6d7df98 a101e48b b3757b04 c5710e04 5720b3c2 fe674f54 73e10ad4 ee722d3e 42244b6d c5099ac4 89dfda90 75fae62a aa733872 c8180d>
Decryption

Use server private key and client public key for decryption:

// base64 encoded keys
let serverPrivateKeyString: String = "UkVDMgAAAC1FsVa6AMGljYqtNWQ+7r4RjXTabLZxZ/14EXmi6ec2e1vrCmyR"
let clientPublicKeyString: String = "VUVDMgAAAC1SsL32Axjosnf2XXUwm/4WxPlZauQ+v+0eOOjpwMN/EO+Huh5d"

guard let serverPrivateKey: Data = Data(base64Encoded: serverPrivateKeyString,
                                            options: .ignoreUnknownCharacters),
    let clientPublicKey: Data = Data(base64Encoded: clientPublicKeyString,
                                         options: .ignoreUnknownCharacters) else {
    print("Error occurred during base64 encoding", #function)
    return
}

Initialise decrypter:

let decrypter: TSMessage = TSMessage.init(inEncryptModeWithPrivateKey: serverPrivateKey,
                                          peerPublicKey: clientPublicKey)!

Decrypt message:

do {
    let decryptedMessage: Data = try decrypter.unwrapData(encryptedMessage)
    let resultString: String = String(data: decryptedMessage, encoding: .utf8)!
    print("decryptedMessage->\n\(resultString)")

} catch let error as NSError {
    print("Error occurred while decrypting \(error)", #function)
    return
}

Result:

$ - Knock, knock.\n- Who’s there?\n*very long pause...*\n- Java.!
Sign / verify

The only code difference from encrypt/decrypt modes is the initialiser methods.

let encrypter: TSMessage = TSMessage.init(inSignVerifyModeWithPrivateKey: clientPrivateKey,
                                          peerPublicKey: serverPublicKey)!

let decrypter: TSMessage = TSMessage.init(inSignVerifyModeWithPrivateKey: serverPrivateKey,
                                          peerPublicKey: clientPublicKey)!

Secure Cell

The Secure Сell functions provide the means of protection for arbitrary data contained in stores, such as database records or filesystem files. These functions provide both strong symmetric encryption and data authentication mechanisms.

The general approach is that given:

  • input: some source data to protect
  • key: a password
  • context: plus an optional "context information"

Secure Cell functions will produce:

  • cell: the encrypted data
  • authentication tag: some authentication data

The purpose of the optional "context information" (i.e. a database row number or filename) is to establish a secure association between this context and the protected data. In short, even when the password is known, if the context is incorrect, the decryption will fail.

The purpose of using the authentication data is to validate that given a correct password (and context), the decrypted data is indeed the same as the original source data.

The authentication data must be stored somewhere. The most convenient way is to simply append it to the encrypted data, but this is not always possible due to the storage architecture of your application. The Secure Cell functions offer variants that address this issue in different ways.

The encryption algorithm used by Secure Cell (by default) is AES-256. The length of the generated authentication data is 16 bytes.

Secure Cell is available in 3 modes:

  • Seal mode: the mode that is the most secure and easy to use. This is your best choice most of the time.
  • Token protect mode: the mode that is the most secure and easy to use. Also your best choice most of the time.
  • Context imprint mode: length-preserving version of Secure Cell with no additional data stored. Should be used carefully.

You can learn more about the underlying considerations, limitations, and features.

Initialising Secure Cell

To initialise Secure Cell object, use master key in Data format:

let masterKeyString: String = "UkVDMgAAAC13PCVZAKOczZXUpvkhsC+xvwWnv3CLmlG0Wzy8ZBMnT+2yx/dg"
let masterKeyData: Data = Data(base64Encoded: masterKeyString, options: .ignoreUnknownCharacters)!
Secure Cell Seal Mode

Initialise encrypter/decrypter:

guard let cellSeal: TSCellSeal = TSCellSeal(key: masterKeyData) else {
    print("Error occurred while initializing object cellSeal", #function)
    return
}

Encrypt:

let message: String = "All your base are belong to us!"
let context: String = "For great justice"

var encryptedMessage: Data = Data()
do {
    // context is optional parameter and may be ignored
    encryptedMessage = try cellSeal.wrap(message.data(using: .utf8)!,
                                         context: context.data(using: .utf8)!)
    print("decryptedMessagez = \(encryptedMessage)")

} catch let error as NSError {
    print("Error occurred while encrypting \(error)", #function)
    return
}

Decrypt:

let context: String = "For great justice"
do {
    let decryptedMessage: Data = try cellSeal.unwrapData(encryptedMessage,
                                               context: context.data(using: .utf8)!)
    let resultString: String = String(data: decryptedMessage, encoding: .utf8)!
    print("decryptedMessage = \(resultString)")

} catch let error as NSError {
    print("Error occurred while decrypting \(error)", #function)
    return
}
Secure Cell Token-protect Mode

Initialise encrypter/decrypter

guard let cellToken: TSCellToken = TSCellToken(key: masterKeyData) else {
    print("Error occurred while initializing object cellToken", #function)
    return
}

Encrypt:

let message: String = "Roses are grey. Violets are grey."
let context: String = "I'm a dog"

var encryptedMessage: TSCellTokenEncryptedData = TSCellTokenEncryptedData()
do {
    // context is optional parameter and may be ignored
    encryptedMessage = try cellToken.wrap(message.data(using: .utf8)!,
                                          context: context.data(using: .utf8)!)
    print("encryptedMessage.cipher = \(encryptedMessage.cipherText)")
    print("encryptedMessage.token = \(encryptedMessage.token)")

} catch let error as NSError {
    print("Error occurred while encrypting \(error)", #function)
    return
}

Decrypt:

let context: String = "I'm a dog"
do {
    let decryptedMessage: Data = try cellToken.unwrapData(encryptedMessage,
                                                          context: context.data(using: .utf8)!)
    let resultString: String = String(data: decryptedMessage, encoding: .utf8)!
    print("decryptedMessage = \(resultString)")

} catch let error as NSError {
    print("Error occurred while decrypting \(error)", #function)
    return
}
Secure Cell Context-Imprint Mode

Initialise encrypter/decrypter

guard let contextImprint: TSCellContextImprint = TSCellContextImprint(key: masterKeyData) else {
    print("Error occurred while initializing object contextImprint", #function)
    return
}

Encrypt

let message: String = "Roses are red. My name is Dave. This poem have no sense"
let context: String = "Microwave"

var encryptedMessage: Data = Data()
do {
    // context is a REQUIRED parameter here
    encryptedMessage = try contextImprint.wrap(message.data(using: .utf8)!,
                                               context: context.data(using: .utf8)!)
    print("encryptedMessage = \(encryptedMessage)")

} catch let error as NSError {
    print("Error occurred while encrypting \(error)", #function)
    return
}

Decrypt

let context: String = "Microwave"
do {
    // context is a REQUIRED parameter here
    let decryptedMessage: Data = try contextImprint.unwrapData(encryptedMessage,
                                                               context: context.data(using: .utf8)!)
    let resultString: String = String(data: decryptedMessage, encoding: .utf8)!
    print("decryptedMessage = \(resultString)")

} catch let error as NSError {
    print("Error occurred while decrypting \(error)", #function)
    return
}

Secure Session

Secure Session is a sequence- and session- dependent, stateful messaging system. It is suitable for protecting long-lived peer-to-peer message exchanges where the secure data exchange is bound to a specific session context.

Secure Session operates in two stages: session negotiation where the keys are established and cryptographic material is exchanged to generate ephemeral keys and data exchange the where exchanging of messages can be carried out between peers.

You can read a more detailed description of the process.

Put simply, Secure Session takes place as follows:

  • Both clients and server construct a Secure Session object, providing
    • an arbitrary identifier,
    • a private key, and
    • a callback function that enables it to acquire the public key of the peers with which they may establish communication.
  • The client will generate a "connection request" and will dispatch that to the server by whatever means available.
  • The server will enter a negotiation phase in response to the client's "connection request".
  • Clients and servers will exchange messages until a "connection" is established.
  • Once a connection is established, clients and servers may exchange secure messages according to whatever application level protocol was chosen.
Secure Session workflow

Secure Session has two parts that are called client and server for the sake of simplicity, but they could be more precisely called initiator and acceptor - the only difference between them is in who starts the communication.

Secure Session relies on the user's passing a number of callback functions to send/receive messages - and the keys are retrieved from local storage (see more in Secure Session cryptosystem description).

Generate keys

Generate client public and private key. Public key should be sent to the server, and private key is used to initialise Session.

guard let keyGeneratorEC: TSKeyGen = TSKeyGen(algorithm: .EC) else {
    print("Error occurred while initializing object keyGeneratorEC", #function)
    return
}
let privateKeyEC: Data = keyGeneratorEC.privateKey as Data
let publicKeyEC: Data = keyGeneratorEC.publicKey as Data

let privateKeyECString = privateKeyEC.base64EncodedString(options: .lineLength64Characters)
let publicKeyECString = publicKeyEC.base64EncodedString(options: .lineLength64Characters)
Initialise Secure Session

ClientId can be obtained from the server or is generated by the client. You can play with Themis Interactive Simulator to get the keys and simulate whole client-server communication.

guard let clientIdData: Data = clientId.data(using: String.Encoding.utf8),
    let clientPrivateKey: Data = Data(base64Encoded: kClientPrivateKey,
                                          options: .ignoreUnknownCharacters) else {
    print("Error occurred during base64 encoding", #function)
    return
}

self.transport = Transport()
self.transport?.setupKeys(kServerId, serverPublicKey: kServerPublicKey)
self.session = TSSession(userId: clientIdData, privateKey: clientPrivateKey, callbacks: self.transport!)
Transport callback

Implement transport callback to return server's public key. Transport layer only returns server public key for requests pointed on serverId.

final class Transport: TSSessionTransportInterface {

    fileprivate var serverId: String?
    fileprivate var serverPublicKeyData: Data?

    func setupKeys(_ serverId: String, serverPublicKey: String) {
        self.serverId = serverId
        self.serverPublicKeyData = Data(base64Encoded: serverPublicKey,
                                          options: .ignoreUnknownCharacters)
    }

    override func publicKey(for binaryId: Data!) throws -> Data {
        let error: Error = NSError(domain: "com.themisserver.example", code: -1, userInfo: nil)
        let stringFromData = String(data: binaryId, encoding: String.Encoding.utf8)
        if stringFromData == nil {
            throw error
        }

        if stringFromData == serverId {
            guard let resultData: Data = serverPublicKeyData else {
                throw error
            }
            return resultData
        }

        return Data()
    }
}
Connect Secure Session
var connectionMessage: Data
do {
    guard let resultOfConnectionRequest = try session?.connectRequest() else {
        throw NSError(domain: "com.themisserver.example", code: -2, userInfo: nil)
    }

    connectionMessage = resultOfConnectionRequest
} catch let error {
    print("Error occurred while connecting to session \(error)", #function)
    return
}

// send `connectionMessage` to the server

Client should send sessionEstablishinData, get response and check if isSessionEstablished before sending payload.

let data: Data = ... // received server response data after sending `connectionMessage`

do {
    guard let decryptedMessage = try self.session?.unwrapData(data) else {
        throw NSError(domain: "com.themisserver.example", code: -4, userInfo: nil)
    }

    if let session = self.session, session.isSessionEstablished() == true {
        print("Session established!")
        // session is established: send payload
    } else {
        // session is NOT established yet, send `decryptedMessage` to the server again
    }
} catch let error {
    ...
}

After the loop finishes, Secure Session is established and is ready to be used.

Send and receive data
var encryptedMessage: Data
do {
    guard let wrappedMessage: Data = try self.session?.wrap(message.data(using: String.Encoding.utf8)) else {
        print("Error occurred during wrapping message ", #function)
        return
    }
    encryptedMessage = wrappedMessage

    // send `encryptedMessage` to the server
} catch let error {
    print("Error occurred while wrapping message \(error)", #function)
}

...

do {
    guard let decryptedMessage: Data = try self.session?.unwrapData(data),
            let resultString: String = String(data: decryptedMessage, encoding: String.Encoding.utf8) else {

        // handle error
    }
    // resultString contains server response 

} catch let error {
    print("Error occurred while decrypting message \(error)", #function)
}

This is it. See the full example available in docs/examples/Themis-server/swift

Secure Comparator

Secure Comparator is an interactive protocol for two parties that compares whether they share the same secret or not. It is built around a Zero Knowledge Proof-based protocol (Socialist Millionaire's Protocol), with a number of security enhancements.

Secure Comparator is transport-agnostic and only requires the user(s) to pass messages in a certain sequence. The protocol itself is ingrained into the functions and requires minimal integration efforts from the developer.

Secure Comparator workflow

Secure Comparator has two parties — called client and server — the only difference between them is in who starts the comparison.

First of all, make sure, that you have enabled Secure Comparator, check steps described above.

Secure Comparator client
let sharedMessage = "shared secret"
let client: TSComparator = TSComparator.init(messageToCompare: sharedMessage.data(using: .utf8)!)!

var data = try? client.beginCompare()

while (client.status() == TSComparatorStateType.comparatorNotReady ) {
    // send data on server and receive response
    self.sendDataOnServer(data)
    data = self.receiveServerResponse()

    // proceed and send again
    data = try? client.proceedCompare(data)
}

After the loop finishes, the comparison is over and its result can be checked calling status:

if (client.status() == TSComparatorStateType.comparatorMatch) {
    // secrets match
    print("SecureComparator secrets match")
} else {
    // secrets don't match
    print("SecureComparator secrets do not match")
}
Secure Comparator server

Server part can be described in any language, let's pretend that both client and server are using Swift.

let sharedMessage = "shared secret"
let server: TSComparator = TSComparator.init(messageToCompare: sharedMessage.data(using: .utf8)!)!

var data: Data

while (server.status() == TSComparatorStateType.comparatorNotReady) {
    // receive from client
    data = self.receiveFromClient

    // proceed and send again
    data = try? server.proceedCompare(data)
}

After the loop finishes, the comparison is over and its result can be checked calling status:

if (server.status() == TSComparatorStateType.comparatorMatch) {
    // secrets match
    print("SecureComparator secrets match")
} else {
    // secrets don't match
    print("SecureComparator secrets do not match")
}