Using Themis in Ruby

Introduction

The Ruby extension 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 the key choice), AES GCM containers.
  • Secure Storage (aka Secure Cell): provides secure storage of record-based data through symmetric encryption and data authentication. AES GCM / AES CTR container.
  • Secure Session: establishing a session between two peers, within which the data can be securely exchanged with higher security guarantees. EC + ECDH, AES containers.

There are also example console utils available for the Ruby wrapper for Themis (as well as for some other wrappers — see the full list here). They help understand the specific mechanics of encryption/decryption processes of this specific wrapper. You can find the example console utils for the Ruby wrapper here.

Quickstart

Building Themis for Ruby

Requirements

In addition to the common set of build tools, Themis currently requires either the OpenSSL or LibreSSL package with the developer version of the package (because it provides header files). In either case, we strongly recommend you using the most recent version of these packages.

Installing Themis

Get the source code of Themis from GitHub:

git clone https://github.com/cossacklabs/themis.git

Note that the default installation process assumes the use of the standard LibreSSL/OpenSSL library and will install Themis to the standard /usr/lib and /usr/include locations.

In a typical case, all you need to do is:

make && sudo make install

If your installation path is different, please see Building and installing for more details on how to change it.

To build and run tests, you can use:

make test

All the tests need to be passed with no errors.

Installing Rubythemis

To install Themis for Ruby, type:

gem install rbthemis

Note: recently we have renamed gem to rbthemis. If you were previously using an older version of rubythemis, please uninstall it from your system using gem uninstall rubythemis before installing rbthemis. This change affects only public gem name, function names and imports remains the same.

You can install rubythemis from the following source:

make rubythemis_install

If you want to install rubythemis in the user folder, use GEM_INSTALL_OPTIONS options:

GEM_INSTALL_OPTIONS=--user-install make rubythemis_install

Importing Themis into your project

Add the following to your code:

require 'rubythemis'

To build and run the Ruby test suit (after its installation), you can use:

make prepare_tests_all test_ruby

Examples

Using Themis

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
class SKeyPairGen
  def ec
  def rsa
end

Description:

  • ec - return private key and public key strings for Elliptic Curve algorithm. Raises ThemisError on failure.

  • rsa - return private key and public key strings for RSA algorithm. Raises ThemisError on failure.

Example
generator = Themis::SKeyPairGen.new
private_key, public_key generator.ec
private_key, public_key generator.rsa

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. It is secure enough for exchanging 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 into 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).

You can read more about Secure Message's cryptographic internals.

Secure Message interface:
class Smessage
  def initialize(private_key, peer_public_key)
  def wrap(message)
  def unwrap(message)
end

def s_sign(private_key, message)
def s_verify(peer_public_key, message)

Description:

  • Smessage - encrypted secure message:

  • initialize(private_key, peer_public_key) - initialise encrypted Secure Message object with private_key and peer_public_key. Raises ThemisError on failure.

  • wrap(message) - wrap message. Return encrypted Secure Message container as a binary string. Raises ThemisError on failure.

  • unwrap(message) - unwrap message. Return decrypted message. Raises ThemisError on failure.

  • signed secure message:

  • s_sign(private_key, message) - Sign message with private_key. Return signed Secure Message container as a binary string. Raises ThemisError on failure.

  • s_verify(peer_public_key, message) - Verify binary string containing signed Secure Message container with public_key. Return plain string. Raises ThemisError on failure.
Example

For a detailed explanation of Secure Message, see Secure Message description.

Initialise encrypter:

smessage = Themis::Smessage.new(private_key, peer_public_key)

Encrypt message:

begin
  encrypted_message = smessage.wrap(message)
rescue ThemisError => e
  # error occured
end

Decrypt message:

begin
  decrypted_message = smessage.unwrap(encrypted_message)
rescue ThemisError => e
  # error occured
end

Sign message:

begin
  signed_message = Themis.s_sign(private_key, message)
rescue ThemisError => e
  # error occured
end

Verify message:

begin
  message = Themis.s_verify(peer_public_key, message_signed_by_peer)
rescue ThemisError => e
  # error occured
end

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.

Secure Cell interface:
class Scell
  def initialize(key, mode)
  def encrypt(message, context = nil)
  def decrypt(message, context = nil)
end

Description:

  • initialize(key, mode) - initialise Secure Cell object with key and mode. mode can be:
  • FULL_MODE - for Seal mode.
  • AUTO_SPLIT_MODE - for Token-protect mode.
  • USER_SPLIT_MODE - for Context-imprint mode.
  • encrypt(message, context = nil) - encrypt message with optional context. Return encrypted string in Seal and Context_imprint modes and an array of two strings (encrypted string and token) in Token-protect mode. Raises ThemisError on failure.
  • decrypt(message, context = nil) - decrypt message with optional context. Return decrypted string. Raises ThemisError on failure.
Examples
Secure Cell Seal Mode

Initialise encrypter/decrypter

scell_full = Themis::Scell.new(key, Themis::Scell::SEAL_MODE)

Encrypt

encrypted_message = scell_full.encrypt(message, context)

Decrypt

decrypted_message = scell_full.decrypt(encrypted_message, context)
Secure Cell Token-protect Mode

Initialise encrypter/decrypter

scell_auto_split = Themis::Scell.new(key, Themis::Scell::TOKEN_PROTECT_MODE)

Encrypt

encrypted_message, additional_auth_data = scell_auto_split.encrypt(message, context)

Decrypt

decrypted_message = scell_auto_split.decrypt([encrypted_message, additional_auth_data], context)
Secure Cell Context-Imprint Mode

Initialise encrypter/decrypter

scell_user_split = Themis::Scell.new(key, Themis::Scell::CONTEXT_IMPRINT_MODE)

Encrypt

encrypted_message = scell_user_split.encrypt(message, context)

Decrypt

decrypted_message = scell_user_split.decrypt(encrypted_message, context)

Secure Session

Secure Session is a sequence- and session-dependent, stateful messaging system. It is suitable for protecting long-lasting 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 a 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 interface
class Ssession
  def initialize(id, private_key, transport)
  def established?
  def connect_request
  def wrap(message)
  def unwrap(message)
  def finalize
end

Description: - initialize(id, private_key, transport) - initialise Secure Session object with id, private_key and a transport - refference to callback object with interface:

class transport < Themis::Callbacks
  def get_pub_key_by_id(id) # return public key string assosiated with id
  def send(message) # send message string to peer
  def receive # return receiver from peer message string
end

Raises ThemisError on failure.

  • connect_request - Create connection initialisation message and send it to peer. Raises ThemisError on failure.
  • wrap(message) - return ready for sending encrypted message. Raises ThemisError on failure.
  • unwrap(message) - return a pair with unwrapped message status and unwrapped message. If unwrapped message status is equal to Themis::SEND_AS_IS unwrapped message must be sent to the peer without any corrections. In other cases, an unwrapped message is a plain message received from the peer. Raises ThemisError on failure.
Secure Session Workflow

Secure Session can be used in two ways: - send/receive - when communication flow is fully controlled by a Secure Session object. - wrap/unwrap - when communication is controlled by the user.

NOTE: We consider wrap/unwrap more fit for typical Ruby frameworks (we've looked into Ruby on Rails and Eventmachine), so the present examples are for wrap/unwrap only. However, if you find that a fully-automatic send/receive might be a good use case for something, let us know.

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 a local storage (see more in Secure Session cryptosystem description).

Wrap/Unwrap

Initialise callbacks class:

class CallbacksForThemis < Themis::Callbacks
  def get_pub_key_by_id(id)
    # retrieve public_key for id from trusted storage (file, db, etc.)
    return public_key
  end
end
Secure Session client

First, initialisation:

@callbacks = CallbacksForThemis.new
@session = Themis::Ssession.new(id, client_private_key, @callbacks)

# key method call - it is a client
connect_request = @session.connect_request

# send connect_request to server
# receive message from server
res, message = @session.unwrap(message)

while res == Themis::SEND_AS_IS
  # send message to server
end

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

To encrypt an outgoing message, use:

# send encrypted_message by any prefered method
encrypted_message = @session.wrap(message)

To decrypt the received message, use:

# receive encrypted_message from peer
message = session.unwrap(encrypted_message)
Secure Session server

First, initialise everything.

@callbacks = CallbacksForThemis.new
@session = Themis::Ssession.new(id, server_private_key, @callbacks)

# there is not connect_request call - it is a server
# receive message from client
res, message = @session.unwrap(message)
while res == Themis::SEND_AS_IS
  # send message to client
end

Secure Session is ready. Sending and receiving encrypted messages are the same.

Send encrypted:

# send encrypted_message by any prefered method
encrypted_message = @session.wrap(message)

Receive and decrypt:

# receive encrypted_message from peer
message = session.unwrap(encrypted_message)

That's it! See the full example available in docs/examples/ruby.

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 interface
class Scomparator
   def initialize(shared_secret)
   def begin_compare
   def proceed_compare(control_message)
   def result
   def finalize
end

Description: - initialize(shared_secret) - initialise secure comparator object with a shared_secret. - begin_compare - return a Secure Comparator initialisation message. - proceed_compare(control_message) - proceed with current and create the next comparation messages (when necessary). - result - return NOT_READY/MATCH/NOT_MATCH result of comparasion.

Secure Comparator workflow

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

Secure Comparator client
@comparator = Themis::Scomparator.new('Test shared secret')

# this call defines the client part
comparation_message = @comparator.begin_compare

while @comparator.result == Themis::Scomparator::NOT_READY do
    user_send_function(comparation_message)
    comparation_message = user_receive_function()

    comparation_message = @comparator.proceed_compare(comparation_message)
end

After the loop finishes, the comparison is over and its result can be checked by calling: @comparator.result.

Secure Comparator server
@comparator = Themis::Scomparator.new('Test shared secret')

while @comparator.result == Themis::Scomparator::NOT_READY do
    comparation_message = user_receive_function()
    comparation_message = @comparator.proceed_compare(comparation_message)
    user_send_function(comparation_message)
end

After the loop finishes, the comparison is over and its result can be checked by calling: @comparator.result.

That's it! See the full example available in docs/examples/ruby.