Вы находитесь на странице: 1из 116

GETTING STARTED

WITH BLACKBERRY
MESSENGER
ENTERPRISE SDK

BUILD WITH THE WORLD'S MOST SECURE MESSAGING PLATFORM


ii Getting Started With BlackBerry Messenger Enterprise SDK

Getting Started With BlackBerry Messenger


Enterprise SDK
All content copyright © 2018 BlackBerry

Cover and design copyright © 2018 SitePoint Pty. Ltd.

Cover Designer: Alex Walker

Notice of Rights
All rights reserved. No part of this book may be reproduced, stored in a retrieval
system or transmitted in any form or by any means, without the prior written
permission of the publisher, except in the case of brief quotations embodied in
critical articles or reviews.

Notice of Liability
The author and publisher have made every effort to ensure the accuracy of the
information herein. However, the information contained in this book is sold
without warranty, either express or implied. Neither the authors and SitePoint
Pty. Ltd., nor its dealers or distributors will be held liable for any damages to be
caused either directly or indirectly by the instructions contained in this book, or
by the software or hardware products described herein.

Trademark Notice
Rather than indicating every occurrence of a trademarked name as such, this
book uses the names only in an editorial fashion and to the benefit of the
trademark owner with no intention of infringement of the trademark.
Getting Started With BlackBerry Messenger Enterprise SDK iii

Published by SitePoint Pty. Ltd.

48 Cambridge Street Collingwood


VIC Australia 3066
Web: www.sitepoint.com
Email: books@sitepoint.com

About SitePoint
SitePoint specializes in publishing fun, practical, and easy-to-understand content
for web professionals. Visit http://www.sitepoint.com/ to access our blogs,
books, newsletters, articles, and community forums. You’ll find a stack of
information on JavaScript, PHP, Ruby, mobile development, design, and more.
iv Getting Started With BlackBerry Messenger Enterprise SDK

Table of Contents
Preface ......................................................................................................................... vii
Architecture Overview .................................................................................................... vii

Features ...................................................................................................................................ix

Example Applications ....................................................................................................xiv

BBMDS: The BBM Data Service Protocol .............................................................. xv

Who Should Read This Book? ...................................................................................xvi

Conventions Used ...........................................................................................................xvi

Chapter 1: Getting Started ................................................................. 19


Getting Started with Android ...................................................................................... 21

Getting Started with iOS ................................................................................................23

Getting Started with Node.js .......................................................................................29

Getting Started with Web .............................................................................................33

Chapter 2: Identity Management ................................................39


OAuth 2.0 ............................................................................................................................... 41

OpenID Connect ................................................................................................................43

Azure Identity Management ........................................................................................44

Configure the BBM Enterprise SDK Domain ........................................................49


Table of Contents v

Chapter 3: User Management Service .................................. 51


Associating Application and BBM Enterprise User Identities ......................52

Contact Discovery and Management......................................................................54

Firebase User Management ........................................................................................55

Azure User Management ..............................................................................................56

Chapter 4: Chats............................................................................................58
Terminology.........................................................................................................................59

Chats .......................................................................................................................................59

Participants ..........................................................................................................................59

Messages ............................................................................................................................. 60

The Lifecycle of a Chat .................................................................................................. 61

Chat Administration .........................................................................................................62

Chat Message Attachments ........................................................................................62

Thumb Attachments .......................................................................................................63

File Attachments ...............................................................................................................64

Chat Message References............................................................................................65

Push Notifications .............................................................................................................78

Chapter 5: Multiple Points of Presence............................... 80


Persistent and Ephemeral Endpoints...................................................................... 81

Endpoint Management ..................................................................................................82

Synchronization .................................................................................................................83
vi Getting Started With BlackBerry Messenger Enterprise SDK

Chapter 6: Statistics Collection....................................................85


Counter ................................................................................................................................. 86

Counter Histogram ...........................................................................................................87

Size Histogram .................................................................................................................. 88

Stat Collection .................................................................................................................... 91

Defined Stats .......................................................................................................................92

Chapter 7: Peer-to-Peer Data Streams .................................97


Data Connection ............................................................................................................... 98

Data Channel...................................................................................................................... 99

Chapter 8: Security ..................................................................................101


Cloud Key Storage......................................................................................................... 102

Cryptography ................................................................................................................... 105

Conclusion .........................................................................................................................116
Preface vii

Preface
The BBM Enterprise SDK provides a framework to develop real-time, end-to-end
secure messaging capabilities in your own product or service.

The BBM Enterprise SDK security model ensures that only the sender and
intended recipients can see each chat message sent, and ensures that
messages aren't modified in transit between the sender and recipient. The BBM
Enterprise SDK also provides the framework for other forms of collaboration and
communication, such as push notifications, secure voice and video calls, and file
sharing. You can even extend and create new types of real-time services and use
cases by defining your own custom application protocols and data types.

Architecture Overview
The BBM Enterprise SDK platform is divided into the following four parts:

The client application


The BBM Enterprise Client SDK
The BBM Enterprise Servers
Additional services provided by you. These services allow the BBM Enterprise
SDK to provide user authentication, facilitate end-to-end secure messaging,
and discovery of other users of the platform.
viii Getting Started With BlackBerry Messenger Enterprise SDK

Application and BBM Enterprise SDK

The BBM Enterprise SDK is included in your application to provide real-time,


end-to-end secure messaging capabilities. The SDK has APIs that allow the
application to authenticate the user, and provide a rich secure communications
platform.

Identity Provider and User Management Service

The BBM Enterprise SDK does not manage user identities or the social network
relationships for the application. The user "accounts" within the BBM Enterprise
SDK represent users only within the SDK. Applications can re-use their existing
user accounts and social network by associating their application accounts to
the BBM Enterprise SDK accounts.

For more detailed and technical information on the Identity Provider or the User
Management Service see Identity Management and User Management Service.

Key Management Service

The BBM Enterprise SDK provides secure messaging and encryption for chats,
Preface ix

voice calls, and video calls. While the BBM Enterprise SDK encrypts and signs
data before it leaves the endpoint, your application is responsible for distributing
security keys between your users.

The BBM Enterprise SDK provides guidance and recommendations on how to


store and share keys between your application's users. This gives your
application complete control over the keys needed to keep your sensitive data
private.

Push Service

Push notifications are an important feature of a real-time applications because


they allow users to be engaged with the application and be notified of everything
from incoming chat messages to incoming voice or video calls. The BBM
Enterprise SDK is built to support push notifications and can generate push
notifications on your behalf, or use your already existing push system. For more
detailed and technical information see Push Notifications.

Features
The BBM Enterprise SDK offers many powerful features to help you build rich
applications easily.

Access Control and Identity

The BBM Enterprise SDK works with your user identity and management
systems to provide strong authentication and authorization. The user accounts
in the BBM Enterprise SDK represent users in the SDK only. The SDK leverages
OAuth and OpenID Connect so it can easily authenticate and associate your
users with their BBM Enterprise SDK accounts.

Read more about identity management.


x Getting Started With BlackBerry Messenger Enterprise SDK

End-To-End Encryption

The BBM Enterprise SDK was designed to comply with the following three
security principles:

Chat messages are digitally signed, so you're assured of who sends each
message in your application.
Chat messages are encrypted, so you're assured that only the intended
recipient can read the message.
Chat messages are subject to integrity signature checks, so you're assured
that the message isn't modified in transit.

Read more about encryption.

Messaging Publish-Subscribe

In the BBM Enterprise SDK, chats are entities that can be created and
manipulated. A chat is a shared space that allows many endpoints to contribute
content in a series of individual chat messages. Typically, these messages
represent user-visible content, but they can also contain arbitrary machine-
readable information that your application can consume. Chat messages can be
both published by and subscribed to by many users and endpoints for real-time
delivery and updates.

Read more about the publish-subscribe model.

Identity Asserted Publishing and Subscribing

The BBM Enterprise SDK controls access so that only authorized participants of
a chat can publish and/or subscribe to content. Chats have administrative rights
that can be assigned to other participants to control who can add more
participants or make other changes.

Read more about the BBM Enterprise SDK security model.


Preface xi

Custom Protocols and Extensions

While it's typical to think of chats and their messages in terms of Instant
Messaging (IM), the APIs in the BBM Enterprise SDK are general purpose and
highly extensible. A chat does not need to represent an IM conversation.
Fundamentally, a chat is a shared space where you can publish custom content
to the subscribers in real time. You can use this to create anything from a shared
whiteboard to a fleet-tracking location service to whatever you can imagine.

Read more about different ways to use the BBM Enterprise SDK.

Rich Chat Experiences

The BBM Enterprise SDK makes it easy for your application to offer a fully-
featured instant messaging experience with:

one-to-one and group chats with chat subjects,


extensible application-defined chat message types,
per-message delivery and read status on a per-participant basis,
per-chat administration roles controlling who can add and remove
participants.

Chat Message History

Participants post messages to the chat. When a message is posted to the chat, it
appears below all of the earlier messages already in the chat. This series of
messages is referred to as the message history. Each chat has its own message
history which is accessible only to participants of the chat.

Read more about chat messages.

Guaranteed Delivery

The BBM Enterprise SDK ensures that a chat message will get from its sender to
xii Getting Started With BlackBerry Messenger Enterprise SDK

the participants of the chat while still offering immediate delivery to online
endpoints. The SDK and infrastructure work together to reconcile their views of
a chat's message history and recover any messages that failed initial delivery.
When messages can't be posted to chats, senders know with clear and definitive
error reporting.

Chat Message Status

The BBM Enterprise SDK reports the delivery status of chat messages they are
first queued, then sent, then delivered, and read. External delivery status is
tracked separately for each participant in each chat across all endpoints.

Chat Message Attachments

Each message in a chat can optionally carry two different kinds of attachments.

A thumb attachment is a small binary payload that is embedded directly into


the chat message and delivered with it.
A file attachment is a large binary payload that is uploaded to cloud storage by
the BBM Enterprise SDK and is referred to by the chat message. Endpoints
that receive the chat message can ask the SDK to download the referenced
file.

Read more about chat message attachments.

Chat Message References

The Chat Message References feature allows you to move beyond a linear view
of the chat history to create richer relationships between chat messages. For
example, you can use Chat Message References to implement any or all of the
following features.

Quoting of older messages by newer ones.


Editing previously sent messages.
Preface xiii

Liking messages.
Adding reactions to messages.
Starting a sidebar conversation thread from a message.
Voting on messages.
Custom message status updates beyond the built in delivered and read.

These are just examples. You can implement many custom behaviors and
features using Chat Message References by setting up rich relationships
between content.

Connection Management

Real-world endpoints aren't always connected. Wi-Fi and mobile network


connections are not completely reliable, and endpoints aren't always able to
maintain a perfect link to the Internet. The BBM Enterprise SDK was built to
expect imperfect connections while optimizing behavior to improve battery life.

Offline Delivery

When BBM Enterprise SDK endpoints reconnect, they automatically reconcile


their data with the infrastructure, catch up, and receive all the traffic that was
sent to them while they were offline.

Multiple Points of Presence

The BBM Enterprise SDK allows your application to have multiple instances
running and connected at the same time for the same user. This ability is
referred to as having Multiple Points of Presence, or MPoP.

Read more about multiple points of presence.

Web Workers

The BBM Enterprise SDK for JavaScript can run as a background task inside a
xiv Getting Started With BlackBerry Messenger Enterprise SDK

Web Worker while your main web application stays in the foreground. This lets
your web application be responsive even while the SDK is busy.

Even when the BBM Enterprise SDK for JavaScript does not run in a Web Worker,
it still offloads expensive work such as network communication and
cryptography to asynchronous tasks that don't block the JavaScript main loop.

Mobile Push Notification: Direct or by Proxy

The BBM Enterprise SDK server supports push notifications to the BBM
Enterprise SDK mobile clients. When new chat messages and incoming calls are
pending delivery to the clients, the server can send a push notification with one
of the following mechanisms:

The BBM Enterprise servers initiate a push request directly to Apple's Push or
Google's GCM/FCM servers.
Your server can initiate push requests to Apple or Google servers.

Read more about mobile push notifications.

Peer-to-Peer Data Streams

With the BBM Enterprise SDK, you can create true peer-to-peer connections
that securely carry encrypted custom application data between two endpoints.
These high-bandwidth connections allow you to create secure, real-time, and
custom media streams or send application-specific protocol messages between
endpoints for any purpose.

Read more about peer-to-peer data streams.

Example Applications
The BBM Enterprise SDK includes some example applications covering all of the
supported BBM Enterprise SDK platforms that you can use to help build your
Preface xv

messaging solution. All of these examples are shipped as part of the SDK
package. Each example application includes a README file to outline features,
prerequisites and a walkthrough.

Some Example Applications are Available on GitHub

Additionally, some of the example applications has a code repository


available at Github.com.

More information on the example applications is available at the BBM Enterprise


SDK Guide.

BBMDS: The BBM Data Service Protocol


BBMDS stands for BBM Data Service and is the name of the JSON message
passing protocol that's used inside the BBM Enterprise SDK on Android and iOS.
The JavaScript version of the SDK does not use BBMDS.

Usually, an application doesn't need to work with BBMDS directly. The SDK APIs
expose a higher-level interface for interacting with the BBM Enterprise SDK.
However, sometimes, applications may benefit from direct access or exposure
to the BBMDS that underpins these APIs.

Enabling BBMDS Logging

When developing or debugging applications, it can be useful to view and


understand the BBMDS JSON messages that are exchanged between the SDK
API layer and the core logic layer of the SDK, known as bbmcore.

See the online FAQ for information on how to enable logging and how to obtain
the log file contents, which will include BBMDS messages.
xvi Getting Started With BlackBerry Messenger Enterprise SDK

Detailed Documentation

The BBMDS Protocol Documentation details the syntax and semantics of the
BBMDS messages.

Who Should Read This Book?


Developers who want to add develop real-time, end-to-end secure messaging
capabilities to their own products or services. You should be familiar with
development in your chosen platform (iOS, Android, Node, or JavaScript) in order
to follow along.

Conventions Used
You’ll notice that we’ve used certain typographic and layout styles throughout
this book to signify different types of information. Look out for the following
items.

Code Samples

Code in this book is displayed using a fixed-width font, like so:

<h1>A Perfect Summer's Day</h1>


<p>It was a lovely day for a walk in the park.
The birds were singing and the kids were all back at school.</p>

Where existing code is required for context, rather than repeat all of it, ⋮ will be
displayed:

function animate() {

new_variable = "Hello";
}
Preface xvii

Some lines of code should be entered on one line, but we’ve had to wrap them
because of page constraints. An ➥ indicates a line break that exists for
formatting purposes only, and should be ignored:

URL.open("http://www.sitepoint.com/responsive-web-
➥design-real-user-testing/?responsive1");
xviii Getting Started With BlackBerry Messenger Enterprise SDK

Tips, Notes, and Warnings

Hey, You!

Tips provide helpful little pointers.

Ahem, Excuse Me ...

Notes are useful asides that are related—but not critical—to the topic
at hand. Think of them as extra tidbits of information.

Make Sure You Always ...

... pay attention to these important points.

Watch Out!

Warnings highlight any gotchas that are likely to trip you up along the
way.

Live Code

This example has a Live Codepen.io Demo you can play with.

Github

This example has a code repository available at Github.com.


Getting Started 19

Chapter

Getting Started
1
20 Getting Started With BlackBerry Messenger Enterprise SDK

You can integrate the BBM Enterprise SDK into your Android, iOS, JavaScript
(Web or Node.js) application by following the steps outlined in the platform
specific guides below. You can download the SDK from the developer resources
page.

To use the BBM Enterprise SDK, you require a registered domain for your
application. The following onboarding steps gather the necessary information
for your BBM Enterprise SDK enabled application to connect to the BBM
Enterprise servers.

Before your application can be deployed in a production environment, you must


complete the following steps:

1 Provide the URL for your Open ID connect UserInfo endpoint.

2 Provide Push Notification details so BBM Enterprise servers can initiate

push notification requests.

The BBM Enterprise SDK contains example applications that demonstrates


basic SDK usage such as:

How to authenticate a user using Open ID Connect


How to start BBM Enterprise SDK services.
Starting a new conversation.
Opening an existing conversation.
Sending and receiving messages in a conversation.
User typing indicators, message delivery and message read receipts.
Voice and Video calling.

Each BBM Enterprise SDK Partner application will be assigned a private domain.
User account creation, authentication and instant messaging will only occur
within your application's domain. This means your application cannot send and
receive messages with BBM Enterprise SDK applications that use other
Getting Started 21

domains, or with the BBM Enterprise standalone application.

Getting Started with Android


This overview will guide you through the steps required to integrate the BBM
Enterprise SDK for Android with your application.

Requirements

Android Studio version 2.0 or later, with SDK API level 19 or higher
Java version 1.7 or later
Android 4.4 or later

Adding BBM Enterprise SDK to your project

Add BBM Enterprise SDK Archive to your project

1 Download and extract the latest version of the BBM Enterprise SDK on

your hard drive.

2 Copy sdk/bbm_sdk-release.aar into your application's libs directory.

Add a dependency on the BBM Enterprise SDK

1 Open the application's app/build.gradle file

2 To add a dependency on the BBM Enterprise SDK, see the sample code

below.

repositories {
flatDir {
dirs 'libs' // This indicates the location of bbm_sdk-release.aar
22 Getting Started With BlackBerry Messenger Enterprise SDK

}
}

dependencies {
compile 'com.google.guava:guava:18.0' // The guava library is required by
➥ the BBM Enterprise SDK
compile (name:'bbm_sdk-release', ext:'aar') // This indicates the dependency on
➥ the BBM Enterprise SDK
...
}

Configure the BBM Enterprise SDK with your registered domain

When you subscribe to use the BBM Enterprise SDK, your application is
assigned a registered domain.

1 Open your application's AndroidManifest.xml

2 To configure the BBM Enterprise SDK with your registered domain, see the

sample code below.

<application

<!-- Configure the BBM Enterprise SDK with the user domain -->
<meta-data android:name="com.bbm.sdk.UserDomain"
➥android:value="MY_USER_DOMAIN"/>

Configure your application to connect to the sandbox development


servers

It is recommended that you do your development and integration testing in the


BBM Enterprise sandbox environment.
Getting Started 23

To point your application to connect to the BBM Enterprise SDK sandbox


environment, add the following to the AndroidManifest.xml :

<application

<!--This is used to point the SDK to either the Production environment or the
Sandbox by default this is pointed to production. If you want to use the Sandbox
environment add the below to your manifest-->
<meta-data android:name="com.bbm.sdk.environment.sandbox" android:value="true"/>

Start the BBM Enterprise SDK

To start the BBM Enterprise SDK, see the sample code below.

// First, you must initialize the BBM Enterprise SDK,


// by passing the application context
BBMEnterprise.getInstance().initialize(getApplicationContext());

// Once initialized, you can start the BBM Enterprise SDK.


BBMEnterprise.getInstance().start();

Further information can be found in the BBM Enterprise SDK guide.

Getting Started with iOS


This overview will guide you through the steps required to integrate the BBM
Enterprise SDK for iOS with your application.

Requirements

Xcode version 8 or later


Deployment target of iOS version 9.0 or later
24 Getting Started With BlackBerry Messenger Enterprise SDK

Install the BBM Enterprise SDK and set up your application

Import the BBM Enterprise SDK into your Xcode project

The BBM Enterprise SDK contains a framework must be imported into your
project:

1 Download and extract the BBM Enterprise SDK archive.

2 Copy the contents of the sdk and sdk-release folders to your Xcode

project folder.

3 Drag BBMEnterprise.Framework into the Frameworks folder of your project

in Xcode.

Use the Correct Version

There are two versions of the framework included with the BBM
Enterprise SDK. The version in sdk includes an i386 and x86_64
simulator segment and as such, is not suitable for submissions to the
App Store. The version in sdk-release contains only the armv7 and
arm64 segments and is suitable for app store submission. When
building your App Store release submission, to ensure the correct
version is embedded in your IPA.

4 Under TARGETS, click the target for your application.

5 At the top of the screen, click Build Settings.

6 In the search text field in the upper right corner of the screen, type

Framework Search Paths.

7 On the left side of the screen, drag the directory in which you placed
Getting Started 25

BBMEnterprise.framework into the Framework Search Paths.

1-1. Dragging the directory into the right place

1 In the search text field in the upper right corner of the screen, type

Bitcode.

2 Next to Enable Bitcode, in the drop-down list, select No.

1-2. Making sure Bitcode in not enabled

1 Drag the BBMEnterprise.framework into the Embedded Binaries section

of the general settings for your application target.


26 Getting Started With BlackBerry Messenger Enterprise SDK

If You're Building for the Simulator

Embed the BBMEnterprise.framework from sdk, not sdk-release, if


building for the simulator.

1 In Xcode, under TARGETS, click the target for your application.

2 At the top of the screen, click Capabilities.

3 Select the check boxes next to all the following modes:

Audio, AirPlay, and Picture in Picture - this allows your application to play
audio alerts when a user receives voice or video calls (each user must grant
permission for the app to use the microphone prior to using it for the first
time.
Voice over IP - this allows your application to make and receive voice and
video calls.

PushKit

PushKit is used for handling push notifications for incoming VoIP


calls. VoIP background mode is obsolete in iOS 10 and Xcode 8.

Remote Notifications - this allows your application to display incoming


messages while the application is running in the background.
Getting Started 27

1-3. Adding background modes

This will add the necessary background modes to your application's Info.plist.

<key>UIBackgroundModes</key>
<array>
<string>voip</string>
<string>audio</string>
<string>remote-notification</string>
</array>

See Apple's programming guide on Background execution for additional


information.

Start BBM Enterprise

To start the BBM Enterprise SDK, see the sample code below. For more info, see
the comments in the sample code below.

// Start BBM Enterprise SDK services by supplying your required unique BBM
//Enterprise domain,which is provided by the BBM Enterprise team when you
//sign up to use the SDK
[[BBMEnterpriseService service] startService:@"<Domain UUID>" environment:kBBM
➥Config_Sandbox completionBlock:^(BOOL success) {
// Update the UI once there is a response.
// Perform any appropriate actions here such as display existing chats
28 Getting Started With BlackBerry Messenger Enterprise SDK

// Once BBM Enterprise SDK services have successfully started,


// you may now invoke BBMEnterprise service API sendAuthToken
}];

The environment parameter will determine which servers the BBM Enterprise
SDK will connect to. When testing your application, you should specify
kBBMConfig_Sandbox as the environment. The application that you ship to
customers should specify kBBMConfig_Production as the environment.

BBM Enterprise Support Classes

Source code for several helper classes can be found in /examples/Support .


Classes and interfaces for handling authentication, key management, and user
management are provided. Where applicable, these classes are written to allow
you to utilize your own back-end storage or authentication scheme. Sample
implementations based on GoogleId/Firebase and Microsoft Azure Active
Directory are provided and used throughout the sample applications.

If using the support code in your application please note the following:

A generic Swift bridging header is included but is written specifically to


support the BBME sample applications. You may need to modify this to
include or exclude the classes you wish to use. If you are not using Firebase or
GoogleId, these specific sections should be omitted for example.
If your application is a Swift application, ensure that you add the path to the
supplied bridging header to the Objective-C Bridging Header bridging
headers location in your project properties or add the relevant classes to your
existing bridging header
Ensure that you add the correct header search paths for the support classes.
Further information can be found in the BBM Enterprise SDK guide.
Getting Started 29

Getting Started with Node.js


This overview will guide you through the steps required to integrate the BBM
Enterprise SDK for Node.js with your application.

This SDK is Isomorphic

This SDK is should be used instead of the BBM Enterprise Web SDK for web
development where development is done with Node.js tooling.

There are some differences between the BBM Enterprise SDK for JavaScript
(Node.js and Web) and the BBM Enterprise SDK for mobile (Android and iOS)
because it is intended to operate in either a web browser or a Node.js
application. These are the important differences:

Data is not stored persistently.

The BBM Enterprise SDK for mobile devices persistently stores all chat
messages and metadata that they receive. The BBM Enterprise SDK for
Javascript caches messages and chat metadata in memory while running, but it
does not store anything persistently. It downloads chat metadata when first
launched, and then downloads messages for a chat on demand only.

Messages are downloaded on demand.

The BBM Enterprise SDK for mobile devices will download all messages during
initial setup. The BBM Enterprise SDK for JavaScript does not, but instead
provides APIs to retrieve only some messages at a time from a specified chat.

Attachments are not downloaded automatically.

The BBM Enterprise SDK for mobile devices automatically downloads any
attachment received, and stores the attachment persistently. The BBM
Enterprise SDK for JavaScript does not download attachments automatically.
30 Getting Started With BlackBerry Messenger Enterprise SDK

Instead, it provides a download function which will retrieve the attachment


attached to a message. The attachments are not cached when they are
downloaded. The client can download the attachment multiple times, but this
could cause a lot of network traffic.

The list of chats may be filtered.

Unlike with the BBM Enterprise SDK for mobile devices, the BBM Enterprise SDK
for JavaScript can be configured to act as if the user is subscribed to a subset of
the chats to which a user has been granted permission. When in this mode, any
message from a chat not on the allowed list is dropped, including invitations to
new chats which are not on the list. The list can be reconfigured at any time to
add chats to which the user already has permission.

Prerequisites

Node.js version 6.0 or later (8.0 or later is recommended)


A native compiler which can be run from node-gyp. Only installing the
compiler needs to be done as per these instructions, the usage of node-gyp is
handled within the SDK.

Adding BBM Enterprise SDK to your project

Install the BBM Enterprise SDK package

1 Download and extract the latest version of the BBM Enterprise SDK to

your hard drive.

2 Initialize a directory structure for a node project by running:

npm init

From the initialized project, run:


Getting Started 31

npm install FILENAME --production

where FILENAME is the path to the file downloaded above.

Content Security Policy

If you want to enable Content Security Policy (CSP), the Content-Security-Policy


HTTPS header value shown below allows the BBM Enterprise SDK to function
correctly. Depending on the implementations chosen, other servers may be
accessed by the authentication, user management or key provider modules, and
may need to be listed as well.

default-src 'self'; connect-src https://*.bbmenterprise.com wss://*.


➥bbmenterprise.com;

Start the BBM Enterprise SDK

In your application, import the BBMEnterprise module:

var BBMEnterprise = require('bbm-enterprise')

Then instantiate the BBM Enterprise SDK by passing the domain, environment,
userId, description, getToken function and getKeyProvider function, and
optionally the nickname and messageStorageFactory.

// Initialize the BBM Enterprise SDK


var messenger = new BBMEnterprise.Messenger({
// The domain provided to you when registering for usage of BBM Enterprise SDK.
// This will be of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. where each X is
// a lowercase character or number.
domain: 'domain'

// It is recommended that you do your development and integration testing


32 Getting Started With BlackBerry Messenger Enterprise SDK

// in the BBM Enterprise sandbox environment.


environment: 'Sandbox'

// This is the identity of the user to log in as, as provided by


// the identity provider module.
userId: 'identifier'

// This function will be called as needed by the SDK to retrieve an


// authentication token.When a token is needed, this function should fetch
// a new one. The SDK will request a token once on startup, but will not
//request again after that until the current token
// becomes invalid. The function should not perform caching of the token.
getToken: function() {...}

// This function returns a KeyProvider corresponding to the KeyProvider interface.


// Please see the JSDoc documentation for a full description of this interface.
getKeyProvider: function() {...}

// A description of the client. This will be used to describe this endpoint when
// using endpoint management functionality. This should never be empty. The
// description can be a maximum of 2000 Unicode Code Points.
description: 'node ' + process.version

// A friendly name in addition to the description. The nickname is optional and


// should be set by a user, if desired.
nickname: 'My node client'

// A storage factory may be chosen based on how the client wants to be notified
// of changes to the message list. The default Immutable storage factory is ideal
// for clients that want to receive messages in immutable list and calculate
// differences from a previous list to see what has changed. The SpliceWatcher
// factory is ideal for clients that want to be notified about what has changed
// through a series of splice calls.
messageStorageFactory: BBMEnterprise.StorageFactory.SpliceWatcher
})

Then, start it.

// Start the BBM Enterprise SDK


messenger.setup()
Getting Started 33

Getting Started with Web


This overview will guide you through the steps required to integrate the BBM
Enterprise SDK for Web with your application.

Don't Use This SDK With Node-based Tooling

This SDK should be used when you want to be able to drop an SDK into a web
page with the inclusion of a <script> tag. Do not use this SDK with Node-based
tooling to process JavaScript modules into a web app. For these tools, use BBM
Enterprise SDK for Node.js, which provides the same functionality in an
isomorphic node package.

There are some differences between the BBM Enterprise SDK for JavaScript
(Node.js and Web) and the BBM Enterprise SDK for mobile (Android and iOS)
because it is intended to operate in either a web browser or a Node.js
application. These are the important differences:

Data is not stored persistently.

The BBM Enterprise SDK for mobile devices persistently stores all chat
messages and metadata that they receive. The BBM Enterprise SDK for
Javascript caches messages and chat metadata in memory while running, but it
does not store anything persistently. It downloads chat metadata when first
launched, and then downloads messages for a chat on demand only.

Messages are downloaded on demand.

The BBM Enterprise SDK for mobile devices will download all messages during
initial setup. The BBM Enterprise SDK for JavaScript does not, but instead
provides APIs to retrieve only some messages at a time from a specified chat.

Attachments are not downloaded automatically.


34 Getting Started With BlackBerry Messenger Enterprise SDK

The BBM Enterprise SDK for mobile devices automatically downloads any
attachment received, and stores the attachment persistently. The BBM
Enterprise SDK for JavaScript does not download attachments automatically.
Instead, it provides a download function which will retrieve the attachment
attached to a message. The attachments are not cached when they are
downloaded. The client can download the attachment multiple times, but this
could cause a lot of network traffic.

The list of chats may be filtered.

Unlike with the BBM Enterprise SDK for mobile devices, the BBM Enterprise SDK
for JavaScript can be configured to act as if the user is subscribed to a subset of
the chats to which a user has been granted permission. When in this mode, any
message from a chat not on the allowed list is dropped, including invitations to
new chats which are not on the list. The list can be reconfigured at any time to
add chats to which the user already has permission.

Prerequisites

A supported browser

The least commonly supported features of browsers used by BBM Enterprise


SDK for Web are:

WebCrypto, including the P-521 ECC algorithm


Promise
Map

In general, all browsers that support these can run BBM Enterprise SDK for web.

Note that WebCrypto is only available in a secure context, so it is recommended


that you serve pages using the BBM Enterprise SDK over HTTPS instead of
HTTP.
Getting Started 35

To check if a browser is supported, call the following function prior to accessing


any other functionality, or requiring the user to log in. This will determine if the
user's browser is compatible with the SDK and allows them to change to another
browser before performing any further steps.:

BBMEnterprise.validateBrowser()

The following browsers are supported:

Google Chrome 59 and newer


Mozilla Firefox 53 and newer

Safari and Microsoft Edge are not supported because they do not include the
P-521 ECC algorithms in WebCrypto. Other than this limitation, the BBM
Enterprise SDK will work on Safari 9 or Edge 16.16299. Although an integrator of
the SDK can add full WebCrypto support to Safari by including a WebCrypto
polyfill prior to the bbm_sdk_web.js script tag, this is strongly not recommended
because the polyfill will reduce the security of the system.

The SDK may be run in a web worker in any supported browser as well as in
Safari (Safari is subject to the same caveat as when not running in a WebWorker).

For Microsoft Edge, there is the additional problem that there is no source of
cryptographically strong random numbers available inside the WebWorker in
Edge. As such, providing a polyfill for WebCrypto getRandomValues API will
probably require passing at least a random number generator seed into the web
worker from outside.

Adding BBM Enterprise SDK to your project

Add BBM Enterprise SDK Archive to your project

1 Download and extract the latest version of the BBM Enterprise SDK to
36 Getting Started With BlackBerry Messenger Enterprise SDK

your hard drive.

2 Copy sdk/bbm_sdk_web.js to your application's directory.

3 In your web page, reference the copied file in a script tag.

<script src="path/to/bbm_sdk_web.js"></script>

This provides access to the global BBMEnterprise object, which can be used to
access BBMEnterprise SDK functionality.

Content Security Policy

If you want to enable Content Security Policy (CSP), the Content-Security-Policy


HTTPS header value shown below allows the BBM Enterprise SDK to function
correctly. Depending on the implementations chosen, other servers may be
accessed by the authentication, user management or key provider modules, and
may need to be listed as well.

default-src 'self'; connect-src https://*.bbmenterprise.com wss://*.


➥bbmenterprise.com;

Start the BBM Enterprise SDK

In your application, initialize the BBM Enterprise SDK by passing the domain,
environment, userId, description, getToken function and getKeyProvider
function, and optionally the nickname and messageStorageFactory.

// Initialize the BBM Enterprise SDK


var messenger = new BBMEnterprise.Messenger({
// The domain provided to you when registering for usage of BBM Enterprise SDK.
// This will be of the form XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX. where each X is
// a lowercase character or number.
Getting Started 37

domain: 'domain'

// It is recommended that you do your development and integration testing


// in the BBM Enterprise sandbox environment.
environment: 'Sandbox'

// This is the identity of the user to log in as, as provided by the identity
// provider module.
userId: 'identifier'

// This function will be called as needed by the SDK to retrieve an authentication


// token. When a token is needed, this function should fetch a new one. The SDK
// will request a token once on startup, but will not request again after that
// until the current token becomes invalid. The function should not perform caching
// of the token.
getToken: function() {...}

// This function returns a KeyProvider corresponding to the KeyProvider interface.


// Please see the JSDoc documentation for a full description of this interface.
getKeyProvider: function() {...}

// A description of the client. This will be used to describe this endpoint when
// using endpoint management functionality. This should never be empty. The
// description can be a maximum of 2000 Unicode Code Points.
description: navigator.userAgent

// A friendly name in addition to the description. The nickname is optional and


// should be set by a user, if desired.
nickname: 'My web client'

// A storage factory may be chosen based on how the client wants to be notified
// of changesto the message list. The default Immutable storage factory is ideal
// for clients thatwant to receive messages in immutable list and calculate
// differences from a previous list to see what has changed. The SpliceWatcher
// factory is ideal for clients that want to be notified about what has changed
// through a series of splice calls.
messageStorageFactory: BBMEnterprise.StorageFactory.SpliceWatcher
})

Then, start it.


38 Getting Started With BlackBerry Messenger Enterprise SDK

// Start the BBM Enterprise SDK


messenger.setup()
Identity Management 39

Chapter

Identity
Management
2
40 Getting Started With BlackBerry Messenger Enterprise SDK

The BBM Enterprise SDK does not manage user identities or contact
relationships for applications. The user accounts in the BBM Enterprise SDK
represent users in the SDK only. The SDK leverages OAuth and OpenID Connect
so it can easily authenticate and associate users to their BBM Enterprise SDK
accounts.

2-1. Architecture Overview - Identity Management

How It Works
To sign in to the application, the user must authenticate with the identity
provider. Next, the application must obtain an OAuth access token or an OpenID
Connect ID token from the identity provider and pass it to the BBM Enterprise
SDK along with the user ID. The BBM Enterprise infrastructure uses the token to
authenticate the user with your identity provider. The BBM Enterprise SDK client
and infrastructure can then communicate using an internal token. The process
repeats when the internal token expires.

The following diagram illustrates the authentication flow in greater detail.


Identity Management 41

2-2. Authentication Flow

The BBM Enterprise SDK supports both OAuth access tokens and OpenID
Connect JWT tokens to authenticate the user with your identity provider. The
information required for the BBM Enterprise SDK to perform the validation is
provided when you register a domain for your application.

OAuth 2.0
For OAuth access tokens, the BBM Enterprise infrastructure must first access
the Token Info service to validate the client_id of the access token. The BBM
Enterprise infrastructure can then access the User Info service to validate the
user ID.

Token Info Endpoint

The BBM Enterprise infrastructure validates that the access tokens provided by
the application are generated by the application's OAuth provider specifically for
the application. This is done by invoking the OAuth provider's Token Info Web
service endpoint to retrieve the client_id of the access token and matching it
42 Getting Started With BlackBerry Messenger Enterprise SDK

with the client_id configured for the application.

BlackBerry recommends following the RFC 7662 Oauth 2.0 Token Introspection
when implementing the Token Info Web service. Additionally, the BBM
Enterprise infrastructure can integrate with a token services that accepts HTTP
GET with an access token parameter and returns the client ID in a JSON
response.

In addition to the service URL, the following configuration items on the Token
Info service are used by the BBM Enterprise infrastructure to invoke the service
and process the response.

Client ID(s): The client_id(s) of an application registered in the application's


OAuth provider.
HTTP method: The HTTP method to use to invoke the service, GET or POST .
If using the GET method, the access token is passed as an URL parameter
access_token . If using the POST method, the access token is passed as an
HTTP body parameter token .
User ID field: The name of the field that contains the user ID in the JSON
response. If the JSON response is composite, a field path in the format
<parent_field>.<child_field>.<user_id_field> can be used.
Client ID field: The name of the field that contains the client_id in the JSON
response. If the JSON response is composite, a field path in the format
<parent_field>.<child_field>.<client_id_field> can be used.
Basic Auth User Name: The user name for HTTP basic authentication if
required.
Basic Auth Password: The password for HTTP basic authentication if
required.

User Info Endpoint

The BBM Enterprise infrastructure validates that the access token provided by
the application belongs to the user. This is done by invoking the User Info Web
Identity Management 43

service endpoint to retrieve the user ID of the access token and matching it with
the user ID provided by the application.

BlackBerry recommends following the OpenID Connect Specification for


UserInfo Endpoint when implementing the User Info Web service. The BBM
Enterprise infrastructure will use the HTTP GET method when issuing the
UserInfo Request.

In addition to the service URL, the User ID field: must also be specified when you
configure the User Info service. The User ID field: is the name of the field that
contains the user ID in the JSON response. If the JSON response is composite, a
field path in the format <parent_field>.<child_field>.<user_id_field> can be
used.

The BBM Enterprise SDK Sample applications demonstrate how to connect to


BBM Enterprise Servers using Google Sign-In.

OpenID Connect
The BBM Enterprise SDK accepts both JWT based ID tokens and access tokens
issued by an OpenID Connect identity provider. Access tokens are
recommended if the application can be registered as an OAuth resource with
explicit scopes the user can grant access to.

The BBM Enterprise infrastructure validates the signature of the JWT tokens
with the public key published by the identity provider. Furthermore, the usage of
the token is validated by its audience, issuer and scopes.

To use JWT tokens, the following configuration is required when registering the
domain for your application.

JWKS URI: The URI of the JWT token signature public keys from the identity
provider.
Issuer Claim Name: The name of the claim for the token issuer. For example,
44 Getting Started With BlackBerry Messenger Enterprise SDK

"iss".
Issuer: The issuer of the claim accepted to access.
User ID Claim Name: The name of the claim for the user ID. For example,
"sub". The claim value is used by the BBM Enterprise SDK as the user ID and it
needs to match the user ID provided by the application.
Expiration Claim Name: The name of the claim for the expiration time. For
example, "exp".
Client ID Claim Name: The name of the claim that carries the client ID(s) the
token is issued for. For example, "aud".
Client IDs: The list of client ID values that are accepted by the BBM Enterprise
infrastructure. A token is accepted when one of the client IDs from the token
belongs to the configured client IDs.
Scope Claim Name: The name of the claim for the access scope. For example,
"scope" or "scp".
Scopes: The list of scope values that are accepted by the BBM Enterprise
infrastructure.

Azure Identity Management


The BBM Enterprise infrastructure can authenticate a user with Azure Active
Directory. If your users already sign in to your app using Azure Active Directory,
you can easily extend the implementation to allow the BBM Enterprise
infrastructure to use Azure Active Directory for access and identity
management.

Authenticating BBM Enterprise Users with Azure Active


Directory

Azure Active Directory supports JSON Web Tokens (JWT). Your app needs to
pass the JWT access token along with the user ID to the BBM Enterprise SDK so
that the user is authenticated against your Azure Active Directory. Your app can
parse the JWT access token returned from the Azure authentication service to
get the Active Directory user ID and other information.
Identity Management 45

In Microsoft Azure, each access token must be used for a specific resource. The
scope parameter sent in the authentication request can contain multiple
permissions, but all the permissions must be for the same resource. The access
token that is used for the BBM Enterprise SDK must not be used for other
resources such as Microsoft Graph API.

Configure Azure for BBM Enterprise SDK

To use Azure Active Directory for authenticating a user with the BBM Enterprise
SDK, follow the steps in the section below to register a Web API with a scope
defining the permission to use BBM Enterprise SDK. This allows the BBM
Enterprise servers to validate the access token that your app received from the
Azure Active Directory authentication service.

Assumption

We're assuming your app will use Azure Active Directory v2.0
authentication API

App Registration

From the Azure Application Registration Portal add a new App.

Make note of the Application Id since that will be needed for other steps.

2-3. Add new app

If developing for the BBM Enterprise JavaScript SDK, add a Web Platform
and enter the path to your redirect page that your application will send as the
46 Getting Started With BlackBerry Messenger Enterprise SDK

redirect_uri parameter to the authorization server. The "Allow Implicit Flow"


check box must be checked.

2-4. Entering the path

Add a Permission Scope for the BBM Enterprise SDK

Continuing in Azure Application Registration Portal, add a permission scope for


the BBM Enterprise SDK.

Leave the default Application ID URI which should be api://<APP_ID>

2-5. Application ID URI

Add a new scope. We recommend using Messaging.All . This must match the
scope you entered in your BBM Enterprise SDK domain's configuration. It
must also match the scope parameter sent in the request from the app to
authenticate with the Azure authorize server.
Identity Management 47

2-6. Adding a new scope

In the Pre-authorized applications section add a application. Enter the App ID


for this app and select the new scope you just added.

2-7. Entering the App ID

Google Sign-In Identity Management

The BBM Enterprise infrastructure can authenticate a user with Google Sign-In.
If your users already sign into your app using Google Sign-In, you can easily
extend the implementation to allow for access and Identity Management with
the BBM Enterprise infrastructure. This example creates a Firebase project to
enable authentication with Google accounts. If your application is not using
Firebase Database for User Management or Cloud Key Storage you can create a
Google API project.

Configure a Firebase Project

To enable authentication with Google Sign-In, we need to create a new Firebase


project. If you have an existing Google API project, you can add Firebase support
to it. Otherwise, select "Add Project" from the Firebase console.

To enable Google Authentication in your Firebase project, select the


48 Getting Started With BlackBerry Messenger Enterprise SDK

"Authentication" page from the sidebar. Open the "Sign-In Method" tab and
toggle the enable switch for the "Google" Sign-in provider.

Copy the Web client ID value, we will use it later to configure your BBM
Enterprise SDK domain.

2-8. Firebase Google Authentication

Open the project settings by clicking the settings cog in the top left corner.
Identity Management 49

2-9. Firebase Project Settings

Add a new app matching the platform of your BBM Enterprise SDK enabled
application.

2-10. Firebase Add App

Configure the BBM Enterprise SDK Domain


Open the BlackBerry application management portal. Choose or create your
BBM Enterprise SDK application. Open the BBM Enterprise tab.

Set the Token Info Endpoint URL to:

https://www.googleapis.com/oauth2/v3/tokeninfo

and the User Info Endpoint to:


50 Getting Started With BlackBerry Messenger Enterprise SDK

https://www.googleapis.com/oauth2/v3/tokeninfo

Copy the client-id value we saved earlier into the OAuth Client ID's field.

2-11. Domain Configuration for Google Sign-In

If you have added an Android application you will need to add the client_id
( client_type 3 ) value from the google-services.json file to the OAuth Client
IDs list.

"oauth_client": [
{
"client_id": "12345678901-umrpbv07n96ck79u5uw1ow04vt4dwza.apps.
➥googleusercontent.com",
"client_type": 3
},
User Management Service 51

Chapter

User
Management
Service 3
52 Getting Started With BlackBerry Messenger Enterprise SDK

The BBM Enterprise SDK does not manage user identities or contact
relationships for applications. The user accounts in the BBM Enterprise SDK
represent users in the SDK only. Your application can reuse existing user
accounts and social networks by associating those application accounts with
BBM Enterprise SDK accounts.

3-1. Architecture Overview - User Management

Associating Application and BBM Enterprise User


Identities
The first time your application client endpoint registers a user with the BBM
Enterprise SDK, an BBM Enterprise SDK account is created for the user. This
new SDK account is assigned a registrationId (regId) that uniquely identifies it
within the BBM Enterprise infrastructure. Your application will remember the
association between the application user and regId in a way that all instances of
your application can find the regId of any application user.

When creating the association between your application user and the regId, your
application will need be able to verify that such an association is genuine. The
BBM Enterprise infrastructure issues a registration token as part of the
User Management Service 53

registration of every endpoint. This registration token is a JWT token signed by


the BBM Enterprise infrastructure that can be validated with the public key
available at one of the JWKS URLs listed below. A trusted part of your application
infrastructure must verify the registration token and use the information it
contains to create a trusted association.

Environment JWKS URL

BBM Enterprise https://discovery.sandbox.bbmenterprise.com/


SDK Sandbox common/your-application-domain/v1/keys/registration

BBM Enterprise https://discovery.shared.bbmenterprise.com/common/


SDK Production your-application-domain/v1/keys/registration

Typically, your application would store these account associations behind a cloud
service accessible to all your application endpoints, and the cloud server that has
the access rights to create those association records would verify the
registration token. Verifying the registration token in an application client
endpoint is not recommended. In order to trust client-based verification, you
would to have complete trust in the integrity of the client before using its result.

The regId assigned to a given application user will not change when your
application registers another endpoint for that user with the BBM Enterprise
SDK.

The registration token body contains the following claims.

sub: The user ID from the application's identity provider.


domain: The BBM Enterprise SDK domain the application is using.
iss: The token issuer. This will be "BBM".
regid: The registration ID of the BBM Enterprise SDK account associated with
the user ID.
exp: The token expiry time.
iat: The token issuing time.
54 Getting Started With BlackBerry Messenger Enterprise SDK

Contact Discovery and Management


Applications will have their own ways of discovering and managing contacts and
relationships. For example, a technical support application may want to allow
communication between its customers and a predefined list of technical support
agents, whereas a chat application may have a list of favorite contacts or
integrate with a corporate address book.

To facilitate the different needs your application may have, the BBM Enterprise
SDK does not manage your user identities. Your application finds contacts or
other user relationships in ways that make sense to you.

For example, to start a chat with a user, your application first locates the target
user in its user account records. Within that record, your application obtains the
associated regId identifier that was securely recorded for that target user when
they first registered their account with the BBM Enterprise SDK. Your application
then asks the SDK to start a chat with that regId.

3-2. User Management Database


User Management Service 55

Firebase User Management


The BBM Enterprise SDK examples include simple user management
implemented using Firebase database. A shared global user list is created by
each user adding and maintaining their own entry in the database.

Firebase User Management Rules

All authorized users can read each entry in the bbmsdk/identity/users table.
Each user may create and edit their own entry in the table which is stored at
bbmsdk/identity/users/$uid. The users table is maintained separately from the
cloud keys. However, cloud keys and users can be stored in the same Firebase
database.

The following rules may be installed into a project's Realtime Database via the
project's Firebase console, which is located at
https://console.firebase.google.com/.

"rules": {
"bbmsdk" : {
"identity": {
//User records can be written by the record creator and read by all
//authenticated users
"users" : {
".read": "auth != null",
"$uid": {
".write": "auth != null && auth.uid == $uid"
}
}
}
}
}
56 Getting Started With BlackBerry Messenger Enterprise SDK

Sample data

Each user entry includes:

avatarUrl : a url where their avatar can be obtained. This must be accessible by
all users.
email
name
regId : their unique registration id assigned by the BBM Enterprise SDK.

"bbmsdk" : {
"identity": {
"UID_1" : {
"avatarUrl" : "https://avatar.com/testavatar.png",
"email" : "test@test.com",
"name" : "John Smith",
"regId" : "123456789000"
},
"UID_2" : {
"avatarUrl" : "https://avatar.com/testavatar2.png",
"email" : "test2@test.com",
"name" : "Jane Doe",
"regId" : "123456789001"
}
}
}

Azure User Management


If you already use Azure Active Directory for identity and access management, it
is easy to extend your app with user discovery and contact management using
the Microsoft Graph API. The BBM Enterprise SDK examples include a user
management implementation using Microsoft Graph API to access Azure Active
Directory.

In Microsoft Azure, each access token must be used for a specific resource. Your
User Management Service 57

app has to authenticate against Azure with a scope containing all Microsoft
Graph API permissions to access Active Directory user data. It cannot reuse the
access token granted for the BBM Enterprise SDK.

Extend Active Directory User Data with BBM Enterprise


Account

The Microsoft Graph API allows an app to access the data of Active Directory
users, and to write custom application data for each user using custom
extensions. In the BBM Enterprise SDK examples, a user's registration ID (regId)
is automatically stored against the user's data in Azure Active Directory. This
allows your app to easily integrate against a corporate directory to facilitate user
lookup, and start secure chat, voice, and video communications using the BBM
Enterprise SDK. Your app can also leverage Microsoft Graph API to manage a
contact list by utilizing user groups or other criteria.

Give your app permission to access Microsoft Graph API

Note: These instructions assume your app will use Azure Active Directory v2.0
authentication API.

From the Microsoft Application Registration Portal, access the Microsoft Graph
Permissions section and add the following:

User.ReadWrite: Required to view the local users data and write the BBM
Enterprise SDK regId to their user entry in Active Directory.
User.ReadBasic.All: Required to view all users in the Active Directory.

3-3. Azure Portal


58 Getting Started With BlackBerry Messenger Enterprise SDK

Chapter

Chats
4
Chats 59

A central feature of the BBM Enterprise SDK is the ability to allow applications to
create chats and share rich messaging experiences. The following section
highlights many of the features of those chats.

Terminology
The BBM Enterprise SDK consists of an identity and its endpoints. An identity is
a user and the endpoints are the identity's client applications that are using the
BBM Enterprise SDK. For more information on identities and endpoints, see
Multiple Points of Presence.

Chats
In the BBM Enterprise SDK, chats are entities that can be created and
manipulated. A chat is a shared space that allows many endpoints to contribute
content in a series of individual messages. Typically, these messages represent
user-visible content, but they can also contain arbitrary information that the
application can consume. The example applications included with the SDK
demonstrate the different ways that messages can be used in chats.

Chats have properties. For example, chats have a subject that can be set and
seen by participants. Chats also have fields that allow applications to attach local
data that is visible only to the local endpoint and fields that allow messages to
reference each other.

Participants
The identities in a chat are called participants. Each participant in a chat has
access to all of the messages and metadata in the chat. This means that if one
participant posts a message to the chat, the message is delivered to all of the
other participants on each of their endpoints. Different chats can have different
participants.

Some participants are administrators and have additional capabilities in the chat.
60 Getting Started With BlackBerry Messenger Enterprise SDK

(See the section on Chat Administrators, below.)

Chats can have as few as one participant, but when a chat loses the last
participant, the chat is deleted.

Because participants can enter and leave chats, participants have a state. When
a participant leaves a chat, the participant's messages aren't deleted. Instead,
the participant's state is updated to indicate that they are no longer in the chat.

Messages
Participants post messages to the chat. When a message is posted to the chat, it
appears below all of the earlier messages already in the chat. This series of
messages is referred to as the message history. Each chat has its own message
history which is accessible only to participants of the chat.

The author of a chat message is referred to as its sender and the act of adding a
message to a chat is referred to as posting the message to the chat.

The application can give each message a type tag to specify how to interpret its
content and metadata on the sending and receiving endpoints.

Messages have many metadata fields, including fields that allow the application
to attach large files or binary payloads, and fields that allow the application to
attach local data visible only to the local endpoint.

Other metadata includes the sender, the time the message was posted, and
information about how other participants have interacted with the message. For
example, every message reports which participants have received the message
and which participants have marked the message as read.

Messages can also be recalled to remove them from receiving endpoints. Or,
messages can be privately deleted so that they are no longer visible to the acting
participant, but remain visible to everyone else.
Chats 61

The Lifecycle of a Chat


Chats are created by the application using the BBM Enterprise SDK. The identity
that creates a chat becomes the first participant. Additional participants can be
invited to join the chat when it is created or they can be added later.

There are two primary kinds of chats.

Normal chats can be between any number of participants, and allow some
participants to be granted administrative capabilities. The same participants
can participate in any number of normal chats.

One-to-one chats exist between two identities. The BBM Enterprise SDK
makes sure that only a single one-to-one chat can exist between the two
identities. When a participant creates a one-to-one chat, the other participant
must be specified when the chat is created, and other participants cannot be
added later. When one of the participants leaves the chat, the other
participant also leaves automatically. At that point, a new one-to-one chat can
be created between the pair of participants.

Participants can join an existing chat when invited by an existing participant.


Chat invitations work on the basis of a grant-and-join mechanism. This means
that the inviting participant's endpoint, the BBM Enterprise infrastructure, and
the invited identity's BBM Enterprise SDK must all agree that the identity should
be allowed into the chat. This mechanism is just one of the ways that BBM
Enterprise makes sure that only authorized identities can join a chat and receive
its messages.

Multiple participants may invite the same identity simultaneously.

Participants can leave a chat at any time. When the last participant leaves a chat,
it is destroyed even within the BBM Enterprise infrastructure.
62 Getting Started With BlackBerry Messenger Enterprise SDK

Chat Administration
The creator of a chat is automatically an administrator of that chat. Chat
administrators have a few additional capabilities that regular participants do not
have. Administrators can:

Promote other participants to be administrators.


Demote other participants from administrators to regular participants.
Remove other participants from the chat without their consent.
Always invite other participants (see below).

When a chat is created, its invitation policy is set by its creator to either allow all
participants to invite others or to allow only administrators to invite others. This
policy cannot be changed while the chat exists. When a chat has an
administrators-only invitation policy but no administrators, then no more
participants can be added to the chat.

Administrators also have the power to destroy chats by removing all other
participants and then leaving the chat.

One-to-one chats do not support administrators or invitation policies.

Chat Message Attachments


Each message in a chat can optionally carry two different kinds of attachments.

A thumb attachment is a small binary payload that is embedded directly into


the chat message and delivered with it.
A file attachment is a large binary payload that is uploaded to cloud storage by
the BBM Enterprise SDK and is referred to by the chat message. Endpoints
that receive the chat message can ask the SDK to download the referenced
file.

Other than its size, the BBM Enterprise SDK places no restrictions on the
Chats 63

content of a thumb or file attachment. It can be any type of text or binary


content, and it will not be examined by the SDK.

All attachments are protected using BBM Enterprise SDK Protect mechanisms.
Attachments can only be received and read by participants of the chat that have
access to the message they are attached to.

Both attachment types preserve their file names (without any directory parts),
subject to some portability and security filtering.

Chat messages also have a data field that can carry arbitrary applications-
specified JSON content. This data is also embedded directly into the chat
message, but it is not considered an attachment in the same sense that a thumb
or file attachment is. In the BBM Enterprise SDK API, attachments are generally
managed as if they are binary files, whereas the data field is presented as a
JSON object property of the chat message.

Thumb Attachments
As its name suggests, a thumb attachment is useful for carrying a small
thumbnail image, such as the small version of a picture. To use a thumb
attachment in this way, your application generates a small image file (such as a
JPEG) with a small resolution and reasonable encoding quality.

When sending a chat message:

On Android and iOS, your application provides the BBM Enterprise SDK with
the path name of a file to be added to the chat message as a thumb
attachment.
In JavaScript, your application provides the thumb attachment data directly.

When a chat message is received, the BBM Enterprise SDK extracts any thumb
attachment.
64 Getting Started With BlackBerry Messenger Enterprise SDK

On Android and iOS, the thumb attachment is placed in a file automatically


and your application is given the path to that file as a property of the chat
message.
In JavaScript, the thumb attachment data is directly available as a property of
the chat message.

A thumb attachment must be no larger than 56320 bytes (55 KB). Its total size is
also subject to a cumulative size limit when combined with the size of the chat
message's data object (encoded as JSON in UTF-8) and the size of the chat
message's content field (in UTF-8). These three fields combined must not
exceed 71680 bytes (70 KB).

Thumb Attachment Counterexample

Thumb attachments would not be a good place to put file type icons. Each
thumb attachment is directly embedded into the delivered chat message and will
be received by and consume storage space on all endpoints of all users in the
chat. So, for file type icons such as "spreadsheet", "document", and
"presentation", an app would be better to know those icons intrinsically and just
display them on each endpoint (perhaps based on hints in the customizable
data JSON object).

File Attachments
A file attachment is the recommended way for applications to send large
content such as documents, full-sized images, or other custom binary payloads
to the participants of a chat.

When sending a chat message:

On Android and iOS, your application provides the BBM Enterprise SDK with
the path name of a file to be added to the chat message as a file attachment.
In JavaScript, your application provides the file attachment data directly.
Chats 65

When a chat message is received, the BBM Enterprise SDK will indicate whether
it has a file attachment. If it does, your application can ask the SDK to download
it either right away or later.

On Android and iOS, a downloaded file attachment is placed in a file


automatically and your application is given the path to that file as a property of
the chat message.
In JavaScript, the downloaded attachment data is never stored as a property
of the chat message. Your application is given the file data in response to the
download request, and your application can manage the lifetime of the
attachment data itself.

A file attachment must be no larger than 128 MB.

Detaching File Attachments

In the BBM Enterprise SDK for Android and iOS, both thumb and file
attachments can be detached from their chat message in order to free space on
an endpoint.

When a thumb attachment is detached, it is removed from the endpoint's local


storage, and cannot be recovered.

When a file attachment is detached, it is removed from the endpoint's local


storage. It can be downloaded again until it expires from cloud storage.

Detaching an attachment is a local operation that has no effect on other


endpoints or participants.

Chat Message References


Fundamentally, chats in the BBM Enterprise SDK consist of a series of chat
messages that were sent by the chat's participants. Chat messages appear in a
certain order, one after the other, as a sequence.
66 Getting Started With BlackBerry Messenger Enterprise SDK

The Chat Message References feature allows you to move beyond this linear
view of the chat history to create richer relationships between chat messages.
For example, you can use Chat Message References to implement any or all of
the following features.

Quoting of older messages by newer ones.


Editing previously sent messages.
Liking messages.
Adding reactions to messages.
Starting a sidebar conversation thread from a message.
Voting on messages.
Custom message status updates beyond the built in delivered and read.

These are just examples. You can implement many custom behaviors and
features using Chat Message References by setting up rich relationships
between content.

What Are Chat Message References?

When your application sends a chat message, it can add a ref property that
contains a list of outgoing references. Each reference in that list consists of:

a tag string that identifies what type of reference it is, and


a target messageId that identifies which chat message is being referenced.

Note that the reference's tag here is separate from the chat message's tag .
The two strings are not related and do not need to use the same values.

A source chat message can refer to many different messages as long as each
reference has a unique tag value. Each reference is represented by an element
in the source chat message's ref list.

The target chat messages referred to by a source chat message's ref list know
Chats 67

that they are the target of a reference. These incoming references are indicated
on a chat message with the refBy property. It contains a list of incoming
references, and each incoming reference has:

a tag that identifies what type of reference it is,


a newestRef that contains the id of the chat message that has most recently
referenced this target chat message with that tag , and
a count that indicates how many other chat messages reference this target
chat message with that tag (including the one identified by newestRef ).

Your application can look at a target chat message and instantly determine
whether it's been referred to by some later message in the chat, and know the
most recent such reference, and whether there are other references between
those two messages. This gives you a lot of power to efficiently draw chat
messages in very different scenarios, as shown in the examples below.

The application can also retrieve the full list of source chat messages that
reference the target chat message with a specific tag .

A Simple Example: "Quote"

The values and meanings of the tag strings are controlled by you, the
application developer. You can impose any meaning that you want on your tags
and the references they create.

For example, say you want to implement chat message quoting. In this feature,
when a user responds to a chat message, they can quote the content of that
original message. When a chat message is quoted in this way, its display is
updated to show the number of times it has been quoted.

To implement this feature, you decide to use a Chat Message References tag
value of Quote to mean that the target chat message has been quoted by the
source chat message.
68 Getting Started With BlackBerry Messenger Enterprise SDK

Assume that the user wants to quote the following existing chat message.

Chat Message Field Name Value

messageId 123

content Using references is easy.

Once the user indicates which existing chat message they want to quote, and
they've entered the content of the quoting message, your application sends a
new chat message that contains a single ref . Assuming that this new chat
message ends up with a message id of 130, it will contain the following fields.

Chat Message Field Name Value

messageId 130

content I agree with this.

ref[0].tag Quote

ref[0].messageId 123

This new quoting chat message is the source chat message in the Chat Message
References relationship.

Note that the quoting messages does not contain the content of the message
that is being quoted; the messages only reference each other. Both the quoted
or quoting message can contain rich content, custom data, thumb or file
attachments, and even other references with other tag values. In this example,
we presume the new quoting message has only the single outgoing reference,
the user's response text, and nothing more, but your application can allow users
to quote and respond with any type of content.

On the sending endpoint and on all receiving endpoints for all participants of the
chat, the quoted chat message (with id 123) gains a refBy list. The quoted
Chats 69

message now looks like this:

Chat Message Field Name Value

messageId 123

content Using references is easy.

refBy[0].tag Quote

refBy[0].newestRef 130

refBy[0].count 1

This indicates that there is an incoming reference referring to this chat message
of type Quote . There is currently only one such reference, and the newest
reference is from chat message 130. Note that the quoted message only gains a
refBy entry and its other fields did not change.

In both the sender and receiver, you decide how you want to draw these chat
messages. In this example, the goal is to show a quote counter on the original
chat message and to draw the new quoting message so that it displays the
content of both the quoted and quoting message.

To draw the quoted message, your application needs to know how many refBy
references there are with the tag Quote . Because refBy is a direct property on
the quoted chat messages, your application makes this drawing decision without
needing any additional data. When there's an incoming Quote reference, you
simply use its count to draw the counter.

To draw the quoting message, your application needs the quoting message's
normal content plus the content of the quoted message so it can include both in
the display. When a chat message has a ref with a tag of Quote , you know it
needs to be drawn as a quoting message. Your application finds the content of
the quoted message by asking the BBM Enterprise SDK for chat message
identified by the ref messageId and then uses the content, attachments, and
70 Getting Started With BlackBerry Messenger Enterprise SDK

other properties of both messages to draw the quoting message however you
want.

As more quoting messages arrive referencing the same quoted message, the
BBM Enterprise SDK increments the count on chat message 123 and reports
the resulting property changes to your application. Your application reacts by
updating its display of the quoted message and drawing the additional quoting
messages in the chat.

Note that the quoting references are created between chat messages sent by
different users. The BBM Enterprise SDK allows cross-user references within
the same chat because it enables simple implementations of features like this
one.

The BBM Enterprise SDK comes with a predefined tag of Quote to help you
build this feature.

4-1. Quoting

Check out the Rich Chat example app for more information on using Chat
Message References to implement message quoting.

A More Involved Example: Message Edits

In this example, suppose that you want to implement an in-place message


editing feature. When a user makes a mistake in a chat message, this feature lets
them fix it by sending an updated version of their message with the error
Chats 71

corrected.

This example only considers the simple text content of chat messages, but Chat
Message References let you build an editing feature where all application-
settable properties of chat messages can be updated. For example, you can use
Chat Message References to let the user update a picture that's attached to a
chat message.

Presume the user has already sent a chat message with id 200 with the
following relevant chat message fields.

Chat Message Field Value

messageId 200

content References are greet.

Unfortunately, the user made a mistake and misspelled "great" as "greet". Your
application lets the user indicate that they want to edit their message and
resend a new copy of it, to be displayed in place of the original. To implement
this, your application forms a new chat message with the following chat
message fields.

Chat Message Field Value

messageId 202

content References are great!

ref[0].tag Edit

ref[0].messageId 200

Remember, the new chat message's messageId field (with value 202) is assigned
by the BBM Enterprise SDK when it is given the message to send. But the
messageId field in the first ref element is set by your application to refer to the
72 Getting Started With BlackBerry Messenger Enterprise SDK

original chat message that the user wants to edit.

In the sender and all receivers, the BBM Enterprise SDK will update chat
message 200 so that it now has a refBy list. Its chat message fields will now be:

Chat Message Field Value

messageId 200

content References are greet.

refBy[0].tag Edit

refBy[0].newestRef 202

refBy[0].count 1

Note that the content field of the original chat message is unchanged. You
haven't lost access to the original text, but, by using the refBy element with the
tag Edit , you have gained access to the revised text.

To draw these chat messages, your application notices the Edit reference on
the original chat message when the BBM Enterprise SDK automatically notifies
it of a property change. In this feature, the goal is to show the most recent
version of the chat message to the user, so your application follows the
newestRef on the original message to find the source of the editing reference,
chat message 202. That chat message has a content field with the revised text,
and your application uses that to draw chat message 200 instead of using the
content field in message 200.

The user can make multiple edits to the chat message. Consider what happens
when the user then sends a second edit for the original, such as:
Chats 73

Chat Message Field Value

messageId 203

content References are awesome!

ref[0].tag Edit

ref[0].messageId 200

The BBM Enterprise SDK automatically updates the properties of the original
chat message so that they are:

Chat Message Field Value

messageId 200

content References are greet.

refBy[0].tag Edit

refBy[0].newestRef 203

refBy[0].count 2

Again, the content of chat message 200 is unchanged, but the newestRef still
refers to a message that does contain the content that needs to be drawn.

You can decide to hide all the Edit reference source chat messages. Or, you can
decide to show them and allow user interaction with them that takes the user
back to the original message. Or, you can draw them only if the original chat
message is off screen and interacting with them could scroll back to show the
edited message.

You can also find all of the edits that have been received for a chat message. This
mechanism will be demonstrated in the next example.

Chat Message References give you a lot of flexibility in how you implement and
74 Getting Started With BlackBerry Messenger Enterprise SDK

display features because you have all the necessary information about message
relationships available, efficiently.

The BBM Enterprise SDK comes with a predefined tag of Edit to help you
build this feature.

Here is an edit in progress that fixes the typo in the word "report":

4-2. Editing a message

Here is the edited message after the typo has been fixed:

4-3. Message is edited


Chats 75

Check out the Announcements example app for more information on using Chat
Message References to implement message editing.

A Complex Example: Threaded Conversations

The previous examples demonstrated how the scalar properties of each


reference on a source or target chat message allow important features to be
implemented simply and flexibly. This example demonstrates the full power of
Chat Message References by add adding one more piece of information: the list
of all source chat messages that refer to a given target chat message.

Suppose you want to allow any arbitrarily chosen message in the chat to become
a "parent" chat message and have "child" chat messages be sent and drawn
under it. Plus, you want to let any "child" message itself become a "parent" for
further nested "child" messages. In other words, you want to allow completely
threaded conversations. You can do this with the BBM Enterprise SDK.

The parent-child relationship is easy to model with the Chat Message


References. The parent is the target chat message and the child is the source
chat message. You can choose a tag of Thread , for example, and use it to
represent these relationships.

A target chat message can have zero or more incoming references, and these
correspond to the zero or more children that a parent message can have. A chat
message can be both a source and a target message for the same tag. These are
all the building blocks necessary to represent the tree of a threaded
conversation:

Parents refer to their children.


Parents can have multiple children.
Children refer to their parents.
Children can also be parents.

Previous examples have already demonstrated how it is efficient for an


76 Getting Started With BlackBerry Messenger Enterprise SDK

application to navigate from children to parents and from parents to their most
recent child. But to draw threaded conversations, your application must be able
to find all children efficiently.

The BBM Enterprise SDK offers an efficient API function to navigate from a
parent to all of its children (with the same tag ). This function takes the tag and
messageId of the parent, and returns full information about each of the child
messages, no matter how far away in the linear history those messages are.

You can decide how to draw threaded conversations. You might allow only one
level of nesting (i.e. sidebar conversations). Or, you might allow arbitrary nesting
but only draw a single level of children by default, requiring manual user
expansion of further nesting levels. Or, you might draw the entire tree of
conversations all the time. Or you could do something completely different.
Again, the choice is up to you.

The BBM Enterprise SDK comes with a predefined tag of Thread to help you
build this feature.
Chats 77

4-4. Threaded conversation

Check out the Threaded Chat example app for more information on using Chat
Message References to build a threaded conversation experience.

Key Points

Chat Message References are implemented by the BBM Enterprise SDK, but
what they mean is up to your application.
A single chat message can refer to multiple other chat messages, as long as
each reference has a unique tag .
A single chat message can be referred to by multiple other chat messages
with the same tag , and can be referred to by more than one tag .
78 Getting Started With BlackBerry Messenger Enterprise SDK

A single chat message can both refer to others and be referred to by others.
References can only be formed to messages in the same chat.
References can only be formed to messages that are known to exist when the
referring chat message is sent. References can be formed to outgoing chat
messages that have not yet been sent.
References can be formed to chat messages from any user. Your application
can enforce per- tag rules about which references it will process. For
example, your application can prohibit (and ignore) outgoing Edit references
from users that are not the author of the referenced chat message.

Push Notifications
The BBM Enterprise SDK server supports push notifications to the BBM
Enterprise SDK mobile clients. When new chat messages and incoming calls are
pending delivery to the clients, the server can send a push notification with one
of the following mechanisms:

1 The BBM Enterprise servers initiate a push request directly to Apple's

Push or Google's GCM/FCM servers.

For Android, you must provide BlackBerry with your application's FCM (GCM)
server keys to allow the BBM Enterprise servers to initiate push requests for
your application.

For iOS, you must provide BlackBerry with your Production VoIP Services
certificates from Apple to allow the BBM Enterprise servers to initiate Apple
push requests for your application.
Chats 79

4-5. Direct push

1 Your server can initiate push requests to Apple/Google servers.

If your server will be initiating the push requests to Apple's Push or Google's
GCM/FCM servers your server will have to implement a simple REST API for the
BBM Enterprise SDK servers to invoke when push delivery to one of your users is
required, using the User Identity token supplied by your Userinfo Endpoint. In
this mechanism, you do not need to share your push credentials with BlackBerry.

4-6. Proxy push


80 Getting Started With BlackBerry Messenger Enterprise SDK

Chapter

Multiple Points
of Presence
5
Multiple Points of Presence 81

The BBM Enterprise SDK allows your application to have multiple instances
running and connected at the same time for the same user. This ability is
referred to as having Multiple Points of Presence, or MPoP.

The BBM Enterprise SDK MPoP feature works by managing two distinct aspects
of a user's representation within the system.

An identity is a user account in the BBM Enterprise infrastructure. Typically


every human user has one account and thus one MPoP identity.

An endpoint is the client application that runs with the credentials, access,
and capabilities of that identity.

In MPoP, each identity can run multiple endpoints simultaneously. Each endpoint
can send and receive messages, start and leave chats, mark messages as read,
etc.

Persistent and Ephemeral Endpoints


The BBM Enterprise SDK supports two kinds of endpoints.

Persistent endpoints are created and exist for a long time. The Android and
iOS versions of the BBM Enterprise SDK are persistent endpoints. Typically,
this type of endpoint exists until the application is uninstalled. When running,
these endpoints are always either connected or waiting to connect to the
BBM Enterprise infrastructure. The endpoints proactively receive messages
and securely store them persistently in local storage.

Ephemeral endpoints are created for a short period of time and come and go
frequently, such as when a web page is loaded and then closed. The Web and
Node versions of the BBM Enterprise SDK are ephemeral endpoints.
Ephemeral endpoints lack persistent storage and often are concerned with
only a small subset of the chats and messages that are available to an identity.
Most importantly, they aren't expected to last for a long time like an installed
82 Getting Started With BlackBerry Messenger Enterprise SDK

Android or iOS application is.

Persistent endpoints can be used offline even when they aren't connected to the
infrastructure. Ephemeral endpoints do not have persistent data so there is only
limited functionality when no connection to the BBM Enterprise infrastructure is
available.

Endpoint Management
The BBM Enterprise SDK limits the number of endpoints of each type that an
identity can have connected to the infrastructure at the same time. The way that
these limits are enforced reflects the differences between the two types of
endpoints.

The BBM Enterprise infrastructure limits each identity to a maximum of three


concurrently registered persistent endpoints and seven concurrently registered
ephemeral endpoints. Your application must expect these limits to change at any
time for new and existing identities. The BBM Enterprise SDK does provide
information about the current limits when performing Endpoint Management.

Persistent Endpoint Management

Persistent endpoints are expected to be entities that the end user is aware of.
For example, a user knows that they have a copy of your application running on
their Android phone and another copy on their iOS tablet. Your application can
use the Endpoint Management features of the BBM Enterprise SDK to list what
endpoints are registered, give each endpoint a name and description, or
deregister an endpoint from their identity.

When a persistent endpoint is created, it first registers with the BBM Enterprise
infrastructure. If it passes various security checks, it is allowed to connect. When
the infrastructure detects that the maximum number of persistent endpoints
has already been reached, your application must deregister one or more of the
existing persistent endpoints to make room for the new one. Alternatively, your
Multiple Points of Presence 83

application can decide to deny the registration of the new endpoint.

Persistent endpoints have the ability to list and manage ephemeral endpoints.

Ephemeral Endpoint Management

The management of ephemeral endpoints is more automatic. These endpoints


are created for brief use, so it is important that they are cheap and easy to make.
When an ephemeral endpoint registers with the BBM Enterprise infrastructure
and the maximum number of ephemeral endpoints has already been reached,
the infrastructure selects a less-active, older ephemeral endpoint and
automatically deregisters it. Ephemeral endpoints that are deregistered do not
automatically try to reregister, but they do allow your application to reregister
them (which might deregister another ephemeral endpoint).

Ephemeral endpoints do not have the ability to list or manage any types of
endpoints.

Synchronization
All endpoints of the same identity see the same data at the same time if they are
all connected to the infrastructure. When endpoints are offline for a short time
and then come back online, they synchronize by receiving messages and other
information from the infrastructure, like a single endpoint does when it
disconnects and then reconnects.

Examples of information that is synchronized across an identity's endpoints


include:

Which chats an identity is participating in and the metadata of those chats,


including the subject and participant list
The messages within a chat
The delivery status ('D' and 'R') of messages for the identity and other
participants
84 Getting Started With BlackBerry Messenger Enterprise SDK

Some state information and data is local to an endpoint and is not synchronized
with other endpoints of the same identity. Sometimes this is because the data
only pertains to the endpoint, and sometimes this is because the state hasn't
propagated to other endpoints yet.

Examples of information that is not synchronized across an identity's endpoints


include:

Chats created locally on an endpoint but not yet created on the server
Chats in the Defunct state
The list of hidden chats
Old chats and old messages that are no longer available from the
infrastructure's storage
Outgoing messages that have not been posted
Failed outgoing messages
Attachments that are not yet uploaded
Attachment upload and download progress
Which attachments are downloaded

Key Synchronization

All endpoints in an identity use the same identity keys and chat keys, and all
endpoints have access to the same user keys.

If your application fetches and stores keys as directed by the BBM Enterprise
SDK, all of these keys are automatically kept in sync through the Cloud Key
Storage mechanism.
Statistics Collection 85

Chapter

Statistics
Collection
6
86 Getting Started With BlackBerry Messenger Enterprise SDK

On Android and iOS devices, the BBM Enterprise SDK records statistics as it
operates. Applications can collect these stats from the SDK and export them via
any compatible statistics aggregation system. The SDK records stats that can be
export by applications for offline analysis and reporting.

Every stat has a name property that indicates what is being measured. Some
stats have a single scalar value, such as a counter, while others have multiple
values. The following subsections describe the different types of stats that the
BBM Enterprise SDK collects.

Counter
The simplest type of stat is the scalar integer. A scalar integer has a single count
value and must be a whole number.

This type of stat is usually used for recording how many times something has
happened, in which case it's referred to as a "counter".

Example Counter

The BBM Enterprise SDK does not currently record any pure counter stats, but
the counter stat forms the basis of some of the other stat types. For example, a
stat named addParticipant could count how many times the local endpoint has
added a participant to any chat. So, if the addParticipant stat had a count of
12 , that would mean that the local endpoint has added 12 participants to chats.

Aggregation of Counters

Generally, counters can be aggregated across multiple endpoints. If an


application sums all of the counters with the same name from all of a user's
endpoints, it can compute how many times that counted event happened on all
of their endpoints.
Statistics Collection 87

In the above example, summing all of the addParticipant stat count values
from all of a user's endpoints would compute how many times the user added a
participant from any endpoint.

Likewise, if an application aggregates counters across multiple users, it can


monitor the entire user population.

Counter Histogram
This stat is a collection of counters that work like a histogram. In addition to its
name , this stat has a set of part and count pairs that record the label and value
for each histogram bucket (i.e. each "part") of the histogram.

Only buckets with non-zero count values will be included in the histogram.

Example Counter Histogram

The stat named msg is a counter histogram that has a part for each of the
message tags that have been sent by the local endpoint. The count associated
with each part counts the number of times a message with that tag has been
sent.

Consider the case where the msg stat has the following values:

part count

Picture 7

Text 102

File 4

This means that the local endpoint sent 7 messages that had a tag of Picture ,
102 messages with a tag of Text , and 4 messages with a tag of File .
88 Getting Started With BlackBerry Messenger Enterprise SDK

For this example stat, the set of part values that will be collected depends on
the set of tag values that the application uses when sending messages.

Aggregation of Counter Histograms

Because they are a collection of counters, counter histograms can be


aggregated in the same way as simple counters.

Using the example above, an application can aggregate the msg histogram to
learn how many different message types a user or set of users is sending.

Size Histogram
A size histogram records information about many instances of a single type of
measurement. Specifically, it is repeatedly measuring the size, in bytes, of a
certain class of thing, such as a file attachment.

Like a counter histogram, this stat has a name and a collection of buckets, each
with a part label and a count . However, with size histograms, each bucket
represents a size milestone.

The part label of each bucket is one of a fixed set of strings such as 4K or
128M . These labels identify the largest size measurement that will be counted in
the bucket. When a size measurement is made, the count of the one largest
bucket whose part is greater than or equal to that measurement is
incremented.

The predefined bucket part labels are described below. Note that the buckets
are somewhat logarithmic, and the first set of buckets cover a smaller size range
than the next set of buckets, and so on. This allows meaningful information to be
captured about a large range of sizes without discarding useful detail at each
particular scale.
Statistics Collection 89

Range Label Note

0 bytes 0K A single bucket where all zero measurements


are counted

4 KB - 16 KB 4K, 8K, ..., 16 buckets of 4 KB width


64K

128 KB - 1 MB 128K, 192K, 15 buckets of 64 KB width


..., 1M

2 MB - 16 MB 2M, 3M, ..., 15 buckets of 1 MB width


16M

32 MB - 256 32M, 48M, ..., 15 buckets of 16 MB width


MB 256M

Larger than 256M+ One bucket for outliers


256 MB

For example, a measurement of 120 KB would be counted in the bucket with the
part label 128K , since it is the bucket for measurements > 64 KB but <= 128 KB.
A measurement of 85 MB would be recorded in the 96M bucket since 85 MB >
80 MB and 85 <= 96 MB.

Note that the kilobytes and megabytes use a traditional definition based on
1024.

Only buckets with non-zero count values will be included in the histogram.

Example Size Histogram

There is an entire set of histograms that are named using the pattern of
msg.file.<tag> , where <tag> is the tag value used by the application when it
sent a message. Each of these histograms measures the different sizes of file
attachment that the local endpoint sent along with messages of the given tag .
90 Getting Started With BlackBerry Messenger Enterprise SDK

For example, the msg.file.Picture histogram measures how large all of the file
attachments are for the Picture -tagged messages sent by the endpoint.
Consider if its buckets were recorded as follows:

part count

256K 1

2M 12

3M 44

4M 36

8M 5

This histogram records a lot of useful information about messages sent with a
tag of Picture .

Firstly, because the 256K bucket has a count value of 1, we know that there was
only 1 attachment that was less than or equal to 256 KB in size.

But, we also know that there were no attachments sent that were less than 192
KB, because if there were, they'd be recorded in smaller buckets (such as the
192K bucket, the 128K bucket, and so on). We don't see any such counters in
those smaller buckets, so we can make this conclusion.

We know that there were 13 attachments that were less or equal to 2 MB in size:
12 in the 2M bucket and 1 in the 256K bucket. We also know that the 12
attachments in the 2M bucket were larger than 256 KB, and that they were all
larger than 1 MB. Otherwise, they would have been counted in other buckets.

We also know that there were 98 attachments sent in total for messages with a
tag of Picture . To compute this, we simply sum all of the bucket count values
in the whole msg.file.Picture histogram.
Statistics Collection 91

Aggregation of Size Histograms

Like the previous stat types, instances of identically named size histograms can
be aggregated across endpoints and users. By summing each bucket with the
same part label, applications can form an aggregate view of the data.

As seen in the above example, this kind of histogram supports an additional kind
of aggregation. Applications can sum all of the buckets in a single instance of the
histogram to learn how many messages with a given tag had an attachment of
any size. This is how the total of 98 was obtained, above. Applications can also
sum all of the buckets in an aggregate of this type of histogram to get a total
count for the set of endpoints and users that the aggregate represents.

The example also showed that sometimes this type of histogram is used to
define a set of related histograms. For example, in the case of those stats with a
name pattern of msg.file.<tag> , applications can also aggregate all members
of this set to find the attachment sizes across all messages with all possible tags.

By aggregating across endpoints, users, buckets, and tags, applications can join
and split the data in various interesting ways to find different kinds of patterns
and behaviors.

Stat Collection
The BBM Enterprise SDK records stats automatically. Applications that want to
use the recorded stats must collect them via the SDK's API and then export
them using a mechanism of the application's choosing.

Periodically, such as once per day, the application on each endpoint should ask
the BBM Enterprise SDK for its current list of recorded stats. The SDK will return
all non-zero counters. The application then exports these values externally, and
once that export has succeeded, it tells the SDK, which in turn resets the
counters so that the next list of recorded stats will only include values that have
been recorded since the previous list was collected.
92 Getting Started With BlackBerry Messenger Enterprise SDK

Through this simple mechanism, stats also obtain a temporal aspect: the counter
values collected "belong to" that specific collection period. The stats remain
locked to that time period and can be analyzed later against other time periods.

Applications should capture user, endpoint, and temporal information when they
collect and export stats to allow richer analysis and reporting options.

See the API Reference for each individual OS for details of how applications can
perform stats collection.

Defined Stats
The following stats are recorded by the current version of the BBM Enterprise
SDK. Stats may be removed or added in future releases as the implementation
and behaviors of the SDK change.

Setup Stats

The setup stat is a counter histogram that has buckets labeled with one of the
following part strings.

part Description

try BBM Setup is being started or retried.

ok BBM Setup has completed successfully.

The setup.err stat is a counter histogram that has buckets labeled with part
strings taken from the BBM Setup API error reasons. This list includes the
following:
Statistics Collection 93

part Description

TemporaryServerError There was a problem with one of the setup steps but it
is possible that a retry will succeed. See the API
documentation for more details.

PermanentServerError There was a serious problem with one of the BBM


setup steps. See the API documentation for more
details.

Forbidden The server forbids this user from registering for an


undisclosed reason. The user id provided in
'setupStart' or 'authToken' might be unusable in the
server ecosystem. See the API documentation for
more details.

CertificateError There was a problem with one of the setup steps due
to a certificate error. See the API documentation for
more details.

REST Stats

Each of the stats described in this section are counter histograms that have
buckets labeled with one of the following part strings.
94 Getting Started With BlackBerry Messenger Enterprise SDK

part Description

try An attempt to issue the request.

ok The request was successful.

0 The request failed without a response.

401 The request encountered an authorization failure.

403 The request was forbidden.

404 The request was attempting to manipulate a non-existent object.

503 The server experienced a temporary timeout.

bbid The request was unable to obtain an authentication token.

http The request experienced some other unspecified HTTPS failure.

The REST counter histograms that use the above part values are as follows.
Statistics Collection 95

name Description

bus.register REST API calls that create a new endpoint.

bus.bbmToken REST API calls to turn SDK application tokens


into BBM tokens.

oly.uploadFile A chat attachment or other file was uploaded to


BlackBerry's secure cloud storage.

oly.downloadFile A chat attachment or other file was downloaded


to BlackBerry's secure cloud storage.

mailbox.create REST API calls to create a chat.

mailbox.update REST API calls to update a chat's metadata.

mailbox.lookup REST API calls to find the metadata of a chat.

mailbox.lookupAll REST API calls to lookup of all subscribed chats.

mailbox.addMember REST API calls to add the current or another user


to a chat.

mailbox.removeMember REST API calls to remove the current or another


user from a chat.

mailbox.addAdmin REST API calls to promote another user to a chat


admin.

mailbox.removeAdmin REST API calls to demote the current or another


user from being a chat admin.

Message Stats

Message Counter Histogram

The msg stat is a counter histogram that has buckets labeled with a dynamic set
of part strings. Each part represents a tag from a chat message that was
sent by the endpoint, so any and all tag values used by the application can
96 Getting Started With BlackBerry Messenger Enterprise SDK

appear as a part .

The count for each part records the number of messages with that tag that
have been sent by the local endpoint.

Attachment Size Histograms

There is an entire set of histograms that are named using the pattern of
msg.file.<tag> , where <tag> is actually the tag value used by the application
when it sent a message. Each of these histograms measures the different sizes
of file attachment that the local endpoint sent along with messages of the given
tag .

There is another set of histograms that are named using the pattern of
msg.thumb.<tag> that measures the sizes of thumb attachments on each
message sent by the local endpoint.

See the example of msg.file.Picture above for a detailed discussion of these


histograms.
Peer-to-Peer Data Streams 97

Chapter

Peer-to-Peer
Data Streams
7
98 Getting Started With BlackBerry Messenger Enterprise SDK

With the BBM Enterprise SDK, you can create true peer-to-peer connections
that securely carry encrypted custom application data between two endpoints.
These high-bandwidth connections allow you to create secure, real-time, and
custom media streams or send application-specific protocol messages between
endpoints for any purpose.

Data Connection
A data connection is a real-time secure connection created as the result of a
data-only call.

Much like a voice or video call, the connection starts with an outgoing request to
the callee carrying an optional meta data. Typically, the meta data contains
description of the data connection for the callee to decide whether or not to
accept the request.

After the incoming request is accepted by the callee, the data connection
makes final security handshakes before making full connectivity. After full
connectivity is made, data over the connection is encrypted using DTLS-SRTP
(see crypto for details) and is peer-to-peer only.

The connection is maintained and kept active while the network path between
the two endpoints remains reachable and there is data flowing. A timeout will
terminate the connection after a number of seconds of inactivity. The number of
seconds varies depending on the platform. If your application requires the
connection to remain active, a pinging mechanism that uses a side data channel
is needed.

Both endpoints of the connection can end the connection at any time. Typically,
if there is no final acknowledgement from the receiver, the recipient should end
the connection upon final data packet arrival.

An established connection could also drop due to network issues, in which case,
Peer-to-Peer Data Streams 99

the connection state will transition to disconnected and the failure reason is
saved.

The following are some of the characteristics of the data connection :

Secure: The connection provides end to end encryption.


Real-time: The data can be transmitted with minimum latency.
Reliable: The ordering of the data is always maintained. Lost data is always re-
transmitted automatically.
Full duplex support: Both endpoints can send and receive freely at the same
time over the same connection.
High bandwidth: Peer-to-peer data transmission allows for maximum
utilization of the bandwidth.
Protocol agnostic: With the Stream type data channel, additional protocol of
signaling, handshaking, data resumption for more complex use cases can be
implemented.

A total of 32 simultaneous data connections are supported and each is


independently encrypted and transmitted.

Data Channel
A data channel sends and receives data of a particular type over a data
connection .

Multiple data channels identified by unique names can be created on a single


data connection . This eliminates the handshakes and negotiation overhead of a
new connection. However, if data segregation is required, creating multiple
data connections is preferred, as each data connection encrypts the data with
a different key.

A Data channel is automatically formed on one endpoint when a sender of a


unique name is created, and is created on the other endpoint as a receiver
100 Getting Started With BlackBerry Messenger Enterprise SDK

when the first packet of the data arrives. Any subsequent data sent over the
same channel will be received by the associated receiver identified by the unique
name.

Some high level types of channels are defined in the table below. Your
application can extend the stream type for more complex use cases as needed.

Large Min Auto


Type Purpose Size
Data latency Termination

File files or large data yes yes no yes

Data data blobs yes no no yes

Stream low latency communication, or no no yes no


user defined

File

A File type data channel allows the sending and receiving of large data blobs.
This channel automatically terminates when the file is fully transmitted.

The underlining buffers are adjusted to allow maximum performance.

Data

A Data type data channel allows the sending and receiving of data blobs. This
channel automatically terminates when the data blob is fully transmitted.

Stream

A Stream type data channel allows the sending and receiving of arbitrary data of
an unknown total size. Data is immediately sent without further buffering, and
the channel stays open until the data connection terminates.
Security 101

Chapter

Security
8
102 Getting Started With BlackBerry Messenger Enterprise SDK

The BBM Enterprise SDK provides secure messaging and encryption for chats,
voice calls, and video calls. While the BBM Enterprise SDK encrypts and signs
data before it leaves the endpoint, your application is responsible for distributing
security keys.

The BBM Enterprise SDK provide guidance and recommendations on how to


store and share keys between your application's users. This gives your
application complete control over the keys needed to keep your sensitive data
private. The BBM Enterprise SDK also comes with example code that
demonstrates how to use popular web-storage solutions like Firebase to
securely distribute keys.

The BBM Enterprise SDK includes APIs to facilitate exporting keys out of the
BBM Enterprise SDK, and importing keys into the BBM Enterprise SDK.

The following types of keys can be exported:

The local user's identity keys (both public and private)


Chat keys

The following types of keys can be imported:

The local user's identity keys (both public and private)


Chat keys
The remote user's identity public keys

Cloud Key Storage


In the BBM Enterprise SDK, messages are protected from being viewed or
modified by anyone other than the sender and intended recipients. The
cryptographic keys used to protect communications are stored and distributed
in a cloud storage system that you choose.

To ensure that your application may use any combination of the SDKs to fulfill its
Security 103

needs, a common storage schema for the encryption, signing, and symmetric
keys must be maintained across all product lines. For example, both the Android
and iOS versions of an application using the BBM Enterprise SDK must be able to
exchange keys, and users must be able to switch between those two versions
without losing their keys.

8-1. Architecture Overview - Key Management

Requirements

The cloud storage system must authenticate users that are using tokens or
credentials managed by your application
The cloud storage system must allow a user to read and write private data
The cloud storage system must allow a user to publish data that other users
can read only

Private data

The cloud storage solution must include restricted read and write access (private
data can only be read or written if the owner of that data is logged into the app).
The following private data must be stored:
104 Getting Started With BlackBerry Messenger Enterprise SDK

The user's private encryption key


The user's private signing key
For each chat
The symmetric encryption key for each of the user’s chats

Public data

The cloud storage solution must include public read access (where public data
can only be read by authenticated users within the ecosystem), and restricted
write access (where private data can only be written if the owner of that data is
logged into the application). The following public data must be stored:

The user's public encryption key


The user's public signing key

Securing Private Keys

Your application should secure exported private key data with a per-user secret
before storing it in the cloud.

The example applications provided with the BBM Enterprise SDK protect all
private key with the following steps:

1 Generate a securely random symmetric encryption key and HMAC key.

These keys will be referred to as the management keys.

2 Use the management keys to encrypt and create a MAC for each private

key data value being stored (AES-256 CTR and HMAC SHA-256 are used in the

provided examples).

3 Store the encrypted bytes, nonce (initialization vector) and MAC for each

key in the cloud.


Security 105

4 Use a key derivation function (KDF) to generate a symmetric encryption

key and HMAC key from a user provided password. The example applications

use ANSI X9.42/X9.63 SHA-512(see Section 3.6.1) as the KDF.

5 Use the keys derived by the KDF to encrypt and create a MAC of the

management keys created in step 1.

6 Store the encrypted management key data created in step 5 in the cloud.

The keys derived by the KDF must not be stored.

7 To recover the private key data use the KDF as in step 3 to re-create

derived keys. Use the derived keys to decrypt the management keys. The

management keys can be used to decrypt the BBM Enterprise SDK private key

data.

8-2. Cloud Key Storage

Cryptography
The BBM Enterprise SDK was designed to comply with the following three
security principles:
106 Getting Started With BlackBerry Messenger Enterprise SDK

Messages are digitally signed, so you're assured of who sends each message
in your application.
Messages are encrypted, so you're assured that only the intended recipient
can read the message.
Messages are subjected to integrity signature checks, so you're assured the
message isn't modified in transit.

The BBM Enterprise SDK will generate two private and public key pairs for each
user, using ECDSA secp521r1: one key pair for signing and one key pair for
encryption. The public signing and encryption keys are distributed to each user
that messages will be exchanged with via BBM SDK Protect - Cloud Key Storage.

All sent messages are encrypted using a per-message key, and signed by the
sender's private signing key. All received messages are verified using the
sender's public signing key, and decrypted using a per-message key. The per-
message keys are generated differently for Identity and Chat messages and are
described below.

In order for your application to function, exported cryptographic keys must be


stored and distributed in a generic storage cloud as per as per BBM SDK Protect
- Cloud Key Storage.

Identity message encryption

Identity messages are messages exchanged between two users outside of a


chat (for instance, an invitation to join a chat from one user to another). Identity
messages are encrypted using a per-message key generated by both the sender
and recipient: the remote user's public encryption key and the local user's private
encryption key are used to generate a ECDH secp521r1 528-bit shared secret.
This shared secret is combined with the message counter and nonce to make a
secret that is used to derive a 32-byte key using ANSI-X9.63-KDF.

The message counter is incremented for each message and the nonce is
randomly generated for each message. These values are sent in the plaintext
Security 107

portion of the protected message.

The derived key is used to encrypt/decrypt the Identity message using AES CTR
mode.

Mathematical Notation

The following demonstrates the mathematical notation of identity message


encryption.

A calculates K_shared = EC-DH(K’enc_A, Kenc_B)

B calculates K_shared = EC-DH(K’enc_B, Kenc_A)

Headers = Nonce (64-bit) || Counter (32-bit) || <other_message_headers>

K_msg = KDF(Headers || K_shared)

Message = Enc_{K_msg, Nonce}(Payload)

Chat message encryption

Chat messages are encrypted using a per-message key generated by both the
sender and recipient. The chat key is sent to the user as a protected identity
message, requesting that the user to join the chat. The chat key is shared via an
invite that is sent as a protected Identity message for the user to join the chat.
The chat key is combined with the message counter and nonce to make the
secret used to derive a 32-byte key using ANSI-X9.63-KDF.

The message counter is incremented for each message, while the nonce is
randomly generated for each message. These values are sent in the plaintext
portion of the protected message.

The derived key is used to encrypt/decrypt the Mailbox message using AES CTR
108 Getting Started With BlackBerry Messenger Enterprise SDK

mode.

Mathematical Notation

The following demonstrates the mathematical notation of chat message


encryption.

Headers = Nonce (64-bit) || Counter (32-bit) || <other_message_headers>

K_msg = KDF(Headers || K_Session)

Message = Enc_{K_msg, Nonce}(Payload)

Signing

Before identity and chat messages are signed, the encrypted data is combined
with the message counter, nonce, and identity information. It is then signed with
the sender's private signing key, using ECDSA secp521r1 SHA-512. The
signature information is sent in the plaintext portion of the protected message,
to be verified by the recipient. The recipient combines the received encrypted
data, message counter and nonce, and identity information to verify it using
ECDSA secp521r1 SHA-512 with the sender's public signing key.

Mathematical Notation

The following demonstrates the mathematical notation of message signing.

Sent Message: Headers || Message || Sign_{Ksign_sender}(Hash( Headers || Message ))

Video, voice, peer-to-peer stream encryption

The BBM Enterprise SDK provides end-to-end security for a real-time video,
voice and peer-to-peer streams, allowing users to place secure voice or video
Security 109

calls or share data. Encryption keys are exchanged using DTLS-SRTP and are
used to secure the SRTP stream of media or the SCTP stream of data.
Additionally, DTLS fingerprints are encrypted and signed using the identity keys
of both participants in the video, voice call or data sharing session, adding
another layer of security and identity verification. Subsequent encryption of the
real-time media stream and peer-to-peer stream follows SRTP specification,
using AES 128 in CTR mode or, in the most recent versions, AES 256 in GCM
mode as a cipher.

WebCrypto

WebCrypto is a standards-track proposal to include cryptographic primitives in


the browser, and has all primitives needed for the BBM Enterprise Web for
JavaScript. WebCrypto has not yet been standardized. Only some browsers
support the standards-track version of WebCrypto. Some other browsers have a
pre-standards-track version of WebCrypto still implemented in native code but
with a slightly different interface. Some browsers have neither.

There are open source third-party shim libraries that provide pure JavaScript
implementation of the WebCrypto interface and fill in any missing pieces that
the browser doesn't support natively, for greater cross browser support. We do
not include such a shim, do to the reduced security compared to a native
implementation.

Primitives

The following WebCrypto primitives are used by BBM Enterprise SDK for
JavaScript:

Generate Signing Key Pair

crypto.subtle.generateKey({ name: 'ECDSA', namedCurve: 'P-521' }, true, ['sign',


➥'verify']);
110 Getting Started With BlackBerry Messenger Enterprise SDK

Generate Encryption Key Pair

crypto.subtle.generateKey({ name: 'ECDH', namedCurve: 'P-521' }, true,


➥['deriveBits']);

Generate Shared Secret

crypto.subtle.deriveBits({ name: 'ECDH', namedCurve: 'P-521', public: publicKey },


➥privateKey, 528);

Sign

crypto.subtle.sign({ name: 'ECDSA', hash: { name: 'SHA-512' } }, importedKey,


➥buildSignData(prefix, data));

Verify

crypto.subtle.verify({ name: 'ECDSA', hash: { name: 'SHA-512' } }, importedKey, sign,


➥buildSignData(prefix, data));

Encrypt

crypto.subtle.encrypt(
{
name: 'AES-CTR',
counter: buildInitVector(nonce),
length: 128
},
derivedKey, plaintext
);

Decrypt

crypto.subtle.decrypt(
Security 111

{
name: 'AES-CTR',
counter: buildInitVector(nonce),
length: 128
},
derivedKey, ciphertext
);

Diagrams

Encryption and Signing

8-3. Encryption and Signing


112 Getting Started With BlackBerry Messenger Enterprise SDK

Data flow: Sending an encrypted and signed message

8-4. Encryption and Signing Encryption


Security 113

When a user sends a message, the BBM Enterprise SDK performs the following
actions:

1 Establishes a 256-bit AES message key from the session key and unique

keying material

2 Encrypts the message with the symmetric key using AES in CTR mode

3 Includes the keying material to recreate the message key in the

unencrypted portion of the message

4 Hashes the whole message using SHA-512

5 Signs the hash with the sender’s private signing key (ECC-521) using

ECDSA

6 Wraps the parts in a message envelope

7 Passes the message to the transport layer


114 Getting Started With BlackBerry Messenger Enterprise SDK

Data flow: Decrypting and verifying a received message

8-5. Decryption and Signing

When a user receives a message, the BBM Enterprise SDK performs the
following actions:

1 Parses the envelope containing the encrypted message

2 Hashes the encrypted message using SHA2-512


Security 115

3 Verifies the message signature using the sender’s public key and the

encrypted message hash; a pass indicates that the message is authentic

4 Derives the message key from the session key and the unencrypted keying

material

5 Decrypts the message using AES in CTR mode

End-to-End View

8-6. End-to-End View


116 Getting Started With BlackBerry Messenger Enterprise SDK

Conclusion
This wraps up our getting started guide to the BlackBerry Messenger Enterprise
SDK. You can find more information in the official documentation, and be sure to
check out the example applications to get ideas for how to integrate the SDK
into your projects.