Virgil Double Ratchet Android SDK

Virgil Security is presenting an implementation of the [Double Ratchet](https://signal.org/docs/specifications/doubleratchet/) algorithm, which is used by parties to exchange encrypted messages based on a shared secret key. The implementation includes: - **Virgil Perfect Forward Secrecy (PFS) service** – a standalone web-service that is dedicated to managing one-time keys and long-time keys that are based on their Identity Public Keys (public keys that are contained in user cards published on Virgil Cards service); - **Ratchet SDK** – interacts with PFS service for publishing and managing one-time keys and long-time keys and interacts with Virgil Cards service for retrieving user's indentity cards which the OTK and LTK are based on. The parties derive new keys for every Double Ratchet message so that previous private keys cannot be calculated from new ones. The parties that participate in the communication also send Diffie-Hellman public values attached to their messages. The results of Diffie-Hellman calculations are mixed into the derived keys so that the new private keys cannot be calculated from the previous ones.

License

License

Virgil Security, Inc. license
Categories

Categories

Security
GroupId

GroupId

com.virgilsecurity
ArtifactId

ArtifactId

ratchet-android
Last Version

Last Version

0.1.4
Release Date

Release Date

Type

Type

aar
Description

Description

Virgil Double Ratchet Android SDK
Virgil Security is presenting an implementation of the [Double Ratchet](https://signal.org/docs/specifications/doubleratchet/) algorithm, which is used by parties to exchange encrypted messages based on a shared secret key. The implementation includes: - **Virgil Perfect Forward Secrecy (PFS) service** – a standalone web-service that is dedicated to managing one-time keys and long-time keys that are based on their Identity Public Keys (public keys that are contained in user cards published on Virgil Cards service); - **Ratchet SDK** – interacts with PFS service for publishing and managing one-time keys and long-time keys and interacts with Virgil Cards service for retrieving user's indentity cards which the OTK and LTK are based on. The parties derive new keys for every Double Ratchet message so that previous private keys cannot be calculated from new ones. The parties that participate in the communication also send Diffie-Hellman public values attached to their messages. The results of Diffie-Hellman calculations are mixed into the derived keys so that the new private keys cannot be calculated from the previous ones.
Project URL

Project URL

https://www.virgilsecurity.com/
Source Code Management

Source Code Management

https://github.com/VirgilSecurity/virgil-ratchet-kotlin

Download ratchet-android

How to add to project

<!-- https://jarcasting.com/artifacts/com.virgilsecurity/ratchet-android/ -->
<dependency>
    <groupId>com.virgilsecurity</groupId>
    <artifactId>ratchet-android</artifactId>
    <version>0.1.4</version>
    <type>aar</type>
</dependency>
// https://jarcasting.com/artifacts/com.virgilsecurity/ratchet-android/
implementation 'com.virgilsecurity:ratchet-android:0.1.4'
// https://jarcasting.com/artifacts/com.virgilsecurity/ratchet-android/
implementation ("com.virgilsecurity:ratchet-android:0.1.4")
'com.virgilsecurity:ratchet-android:aar:0.1.4'
<dependency org="com.virgilsecurity" name="ratchet-android" rev="0.1.4">
  <artifact name="ratchet-android" type="aar" />
</dependency>
@Grapes(
@Grab(group='com.virgilsecurity', module='ratchet-android', version='0.1.4')
)
libraryDependencies += "com.virgilsecurity" % "ratchet-android" % "0.1.4"
[com.virgilsecurity/ratchet-android "0.1.4"]

Dependencies

compile (4)

Group / Artifact Type Version
com.virgilsecurity : ratchet jar 0.1.4
com.virgilsecurity.sdk : sdk-android jar 7.3.1
com.virgilsecurity.sdk : crypto-android jar 7.3.1
com.virgilsecurity.crypto : ratchet-android jar 0.15.2

runtime (2)

Group / Artifact Type Version
org.jetbrains.kotlin : kotlin-android-extensions-runtime jar 1.3.61
org.jetbrains.kotlin : kotlin-stdlib-jdk8 jar 1.3.61

Project Modules

There are no modules declared in this project.

Virgil Security Ratchet Java/Kotlin SDK

Build Status Maven Central GitHub license

Introduction | SDK Features | Installation | Register Users | Peer-to-peer Chat Example | Group Chat Example | Support

Introduction

Virgil Security provides a set of services and open source libraries for adding security to any application. If you're developing a chat application, you'll understand the need for a high level of data protection to ensure confidentiality and data integrity.

You may have heard of our e3kit which offers a high level of end-to-end encription, but if you need maximum protection with your application, Virgil Security presents the Double Ratchet SDK – an implementation of the Double Ratchet Algorithm. With the powerful tools in this SDK, you can protect encrypted data, even if user messages or a private key has been stolen. The Double Ratchet SDK not only assigns a private encryption key with each chat session, but also allows the developer to limit the lifecycle of these keys. In the event an active key is stolen, it will expire according to the predetermined lifecycle you had set in your application.

Ratchet SDK interacts with the PFS service to publish and manage one-time keys (OTK), long-term keys (LTK), and interacts with Virgil Cards service to retrieve the user identity cards the OTK and LTK are based on. The Ratchet SDK issues chat participants new keys for every chat session. As a result new session keys cannot be used to compromise past session keys.

SDK Features

  • communicate with Virgil PFS Service
  • manage users' one-time keys (OTK) and long-term keys (LTK)
  • enable group or peer-to-peer chat encryption
  • uses the Virgil crypto library and Virgil Core SDK

Installation

You can easily add Ratchet SDK dependency to your project with:

Maven

<dependencies>
    <dependency>
        <groupId>com.virgilsecurity</groupId>
        <artifactId>ratchet</artifactId>
        <version><latest-version></version>
    </dependency>
</dependencies>

Gradle

Add jcenter() repository if missing, then update gradle dependencies:

    implementation "com.virgilsecurity:ratchet:<latest-version>"

The <latest-version> of the Ratchet SDK can be found in the Maven Central Repository or in the header of current readme.

Register Users

Make sure you have registered with the Virgil Dashboard and have created an E2EE V5 application.

Besides registering on your own server, users must also be registered on the Virgil Cloud. If they already are, you can skip this step and proceed to the next one.

Every Virgil user has a Virgil Card with an unlimited life-time on their device. The card contains a Private Key, Public Key, and the user's identity.

To register users on the Virgil Cloud (i.e. create and publish their Identity Cards), follow these steps:

  • Set up your backend to generate a JWT to provide your service and users with access to the Virgil Cloud.
  • Set up the client side for authenticating users on the Virgil Cloud.
  • Set up the Cards Manager on your client side to generate and publish Virgil Card with Virgil Cards Service.

If you've already installed the Virgil Ratchet SDK or don't need to install the Virgil SDK or Virgil Crypto, you can use this guide for the steps described above.

Initialize SDK

To begin communicating with the PFS service and establish a secure session, each user must run the initialization. To do that, you need the Receiver's public key (identity card) from Virgil Cloud and the sender's private key from their local storage:

val rotateKeysListener = object : OnResultListener<RotationLog> {
    override fun onSuccess(result: RotationLog) {
        // Keys were rotated
    }

    override fun onError(throwable: Throwable) {
        // Error handling
    }
}

val context = SecureChatContext(identityCard = card,
                                identityKeyPair = keyPair,
                                accessTokenProvider = provider)

val secureChat = SecureChat(context = context)

secureChat.rotateKeys().addCallback(rotateKeysListener)

During the initialization process, using Identity Cards and the rotateKeys method we generate special keys that have their own life-time:

  • One-time Key (OTK) - each time chat participants want to create a session, a single one-time key is obtained and discarded from the server.
  • Long-term Key (LTK) - rotated periodically based on the developer's security considerations and is signed with the Identity Private Key.

Peer-to-peer Chat Example

In this section you'll find out how to build a peer-to-peer chat using the Virgil Ratchet SDK.

Send initial encrypted message

Let's assume Alice wants to start communicating with Bob and wants to send the first message:

  • first, Alice has to create a new chat session by running the startNewSessionAsSender function and specify Bob's Identity Card
  • then, Alice encrypts the initial message using the encrypt SDK function
  • finally, The Ratchet SDK doesn't store and update sessions itself. Alice has to store the generated session locally with the storeSession SDK function.
// prepare a message
val messageToEncrypt = "Hello, Bob!"

val startNewSessionAsSenderListener = object : OnResultListener<SecureSession> {
    override fun onSuccess(session: SecureSession) {
        val ratchetMessage = session.encrypt(messageToEncrypt)
        secureChat.storeSession(session)
        val encryptedMessage ratchetMessage.serialize()
    }

    override fun onError(throwable: Throwable) {
        // Error handling
    }
}

// start new secure session with Bob
secureChat.startNewSessionAsSender(receiverCard = bobCard).addCallback(startNewSessionAsSenderListener)

Important: You need to store the session after operations that change the session's state (encrypt, decrypt), therefore if the session already exists in storage, it will be overwritten

Decrypt the initial message

After Alice generates and stores the chat session, Bob also has to:

  • start the chat session by running the startNewSessionAsReceiver function
  • decrypt the encrypted message using the decrypt SDK function
val ratchetMessage = RatchetMessage.deserialize(encryptedMessage)

val secureSession = secureChat.startNewSessionAsReceiver(senderCard = aliceCard, ratchetMessage = ratchetMessage)

val decryptedMessage = secureSession.decryptString(ratchetMessage)

secureChat.storeSession(session)

Important: You need to store sessions after operations that change the session's state (encrypt, decrypt). If the session already exists in storage, it will be overwritten

Encrypt and decrypt messages

Encrypting messages

To encrypt future messages, use the encrypt function. This function allows you to encrypt data and strings.

You also need to use message serialization to transfer encrypted messages between users. And do not forget to update sessions in storage as their state changes with every encryption operation!

  • Use the following code-snippets to encrypt strings:
val session = secureChat.existingSession(participantIdentity = bobCard.identity)

val message = session.encrypt("Hello, Bob!")

secureChat.storeSession(session)

val messageData = message.serialize()
// Send messageData to Bob
  • Use the following code-snippets to encrypt data:
val session = secureChat.existingSession(participantIdentity = bobCard.identity)

val message = session.encrypt(data)

secureChat.storeSession(session)

val messageData = message.serialize()
// Send messageData to Bob

Decrypting Messages

To decrypt messages, use the decrypt function. This function allows you to decrypt data and strings.

You also need to use message serialization to transfer encrypted messages between users. And do not forget to update sessions in storage as their state changes with every decryption operation!

  • Use the following code-snippets to decrypt strings:
val session = secureChat.existingSession(participantIdentity = aliceCard.identity)

val ratchetMessage = RatchetMessage.deserialize(messageData)

val decryptedMessage = session.decryptString(ratchetMessage)

secureChat.storeSession(session)
  • Use the following code-snippets to decrypt data:
val session = secureChat.existingSession(participantIdentity = aliceCard.identity)

val ratchetMessage = RatchetMessage.deserialize(messageData)

val decryptedMessage = session.decryptData(ratchetMessage)

secureChat.storeSession(session)

Group Chat Example

In this section, you'll find out how to build a group chat using the Virgil Ratchet SDK.

Create Group Chat Ticket

Let's assume Alice wants to start a group chat with Bob and Carol. First, create a new group session ticket by running the startNewGroupSession method. This ticket holds a shared root key for future group encryption. Therefore, it should be encrypted and then transmitted to other group participants. Every group chat should have a unique 32-byte session identifier. We recommend tying this identifier to your unique transport channel id. If your channel id is not 32-bytes you can use SHA-256 to derive a session id from it.

// Create transport channel according to your app logic and get session id from it
val sessionId = ConvertionUtils.hexToBytes("7f4f96cedbbd192ddeb08fbf3a0f5db0da14310c287f630a551364c54864c7fb")

val ticket = secureChat.startNewGroupSession(sessionId)

Start Group Chat Session

Now, start the group session by running the startGroupSession function. This function requires specifying the group chat session ID, the receivers' Virgil Cards and tickets.

val receiverCards = cardManager.searchCards(listOf("Bob", "Carol"))

val groupSession = secureChat.startGroupSession(receiverCards, sessionId, ticket)

Store the Group Session

The Ratchet SDK doesn't store and update the group chat session itself. Use the storeGroupSession SDK function to store the chat sessions.

Also, store existing session after operations that change the session's state (encrypt, decrypt, setParticipants, updateParticipants). If the session already exists in storage, it will be overwritten

secureChat.storeGroupSession(groupSession)

Send the Group Ticket

Next, provide the group chat ticket to other members.

  • First, serialize the ticket
val ticketData = ticket.serialize()
  • For security reasons, we can't send the unprotected ticket because it contains an unencrypted symmetric key. Therefore, we have to encrypt the serialized ticket for the receivers. The only secure way to do this is to use peer-to-peer Double Ratchet sessions with each participant to send the ticket.
receiverCards.forEach { card ->
    val session = secureChat.existingSession(participantIdentity = card.identity) ?:
    // If you don't have session, see Peer-to-peer Chat Example on how to create it as Sender.
    return


    val encryptedTicket = session.encrypt(ticketData).serialize()

    secureChat.storeGroupSession(groupSession)

    // Send ticket to receiver
}
  • Next, use your application's business logic to share the encrypted ticket with the group chat participants.

Join the Group Chat

Now, when we have the group chat created, other participants can join the chat using the group chat ticket.

  • First, we have to decrypt the encrypted ticket
val session = secureChat.existingSession(participantIdentity = "Alice") ?:
// If you don't have a session, see the peer-to-peer chat example on how to create it as a receiver.
return

val encryptedTicketMessage = RatchetMessage.deserialize(encryptedTicket)

val ticketData = session.decryptData(encryptedTicketMessage)
  • Then, use the deserialize function to deserialize the session ticket.
val ticket = RatchetGroupMessage.deserialize(ticketData)
  • Join the group chat by running the startGroupSession function and store the session.
val receiverCards = cardManager.searchCards(listOf("Alice", "Bob"))

val groupSession = secureChat.startGroupSession(receiverCards, sessionId, ticket)

secureChat.storeGroupSession(groupSession)

Encrypt and decrypt messages

Encrypting messages

In order to encrypt messages for the group chat, use the encrypt function. This function allows you to encrypt data and strings. You still need to use message serialization to transfer encrypted messages between users. And do not forget to update sessions in storage as their state is changed with every encryption operation!

  • Use the following code-snippets to encrypt strings:
val message = groupSession.encrypt("Hello, Alice and Bob!")

secureChat.storeGroupSession(groupSession)

val messageData = message.serialize()
// Send messageData to receivers
  • Use the following code-snippets to encrypt data:
val message = groupSession.encrypt(data)

secureChat.storeGroupSession(groupSession)

val messageData = message.serialize()
// Send messageData to receivers

Decrypting Messages

To decrypt messages, use the decrypt function. This function allows you to decrypt data and strings. Do not forget to update sessions in storage as their state changes with every encryption operation!

  • Use the following code-snippets to decrypt strings:
val message = RatchetGroupMessage.deserialize(messageData)

val carolCard = receiversCard.first { it.identity == "Carol" }

val decryptedMessage = groupSession.decryptString(message, senderCardId = carolCard.identifier)

secureChat.storeGroupSession(groupSession)
  • Use the following code-snippets to decrypt data:
val message = RatchetGroupMessage.deserialize(messageData)

val carolCard = receiversCard.first { it.identity == "Carol" }

val data = groupSession.decryptData(message, senderCardId = carolCard.identifier)

secureChat.storeGroupSession(groupSession)

License

This library is released under the 3-clause BSD License.

Support

Our developer support team is here to help you. Find out more information at our Help Center.

You can find us on Twitter or send us an email at [email protected].

Also, get extra help from our support team on Slack.

com.virgilsecurity

Virgil Security, Inc.

Virgil Security, Inc. enables developers to eliminate passwords & encrypt everything, in hours, without having to become security experts.

Versions

Version
0.1.4
0.1.3
0.1.2
0.1.1
0.1.0