DEVELOPERS BLOG

Cryptography APIs – A Gentle Introduction – Random Numbers

dice

Dice Stock Photo graur razvan ionut. / FreeDigitalPhotos.net

Written by:  John Murray (@jcmrim)

Introduction

I don’t know about you but when I first had a need to use the BlackBerry 10 Cryptography Library APIs I found them extremely intimidating. Don’t get me wrong, I understood cryptography and knew what it was that I wanted to achieve: generate a random number, calculate an SH256 hash, or even create RSA key pairs; yet, I found the description of the APIs themselves opaque and getting that first snippet of working code took quite a lot of effort.

Over time I managed to accumulate a number of code fragments for the more common use-cases I came across that I could easily reuse – I’m sure you do the same sort of thing! So, noticing that there were still many questions in the Developer Support Forums I decided to wrap the most common of these code fragments into a sample application to share with the wider community.

I wrote an application called CryptoSample that you can find on GitHub here:

https://github.com/blackberry/Cascades-Community-Samples/tree/master/cryptosample

It demonstrates three common cryptography use-cases using the BlackBerry 10 Cryptography Library APIs:

Generating a simple random number;

  1. Calculating Hashes (SHA1, SHA256) and HMAC using a predefined key;
  2. Using RSA:

a.  Creating an RSA public/private key pair;

b. Creating a self-signed certificate using this pair of keys showing how to select SHA256 as the hash for the RSA certificate signing rather than the default MD5;

c.  Encrypting plaintext and decrypting the resulting cipher text using this pair of keys.

This isn’t intended to be a tutorial on cryptography; if this is what you’re looking for take a look on the web to any of the excellent resources that you’ll find there. These are simply simple implementations of these use cases using the BlackBerry 10 Cryptography Library APIs that can be used to help you in overcoming that barrier of understanding how to use them. I haven’t touched on AES simply because there is already an excellent example in GitHub covering this specific use-case:

https://github.com/blackberry/Cascades-Community-Samples/tree/master/AESCryptoDemo

So, these three topics will be split across three separate Blog Posts simply to divide the whole into a number of bite-sized stories that are easy to digest one at a time.

This is the first of these Blog Posts and it’s all about generating random numbers using the BlackBerry 10 Cryptography Library APIs. So, let’s get started!

Random Numbers

The ability to generate unpredictable random numbers is fundamental to every aspect of cryptography. Good Random Number Generators (RNG) are actually difficult to find! If your application simply needs to generate a “random quote of the day” from, say, a database then you may not be concerned about the level of unpredictability that the RNG provides. If, on the other hand you need to use a random number to generate a pair of public/private keys then unpredictability is much higher up your agenda.

I’m sure we’ve all experienced the shock when we first started playing with random numbers that the list of random numbers produced by our application when naively using the RNG provided by our language of choice consistently generated identical runs of numbers each time we ran the programme! Hmm, incorrectly seeding the RNG is all too easy to overlook

Unpredictability is the key!

So, whilst rand() and srand() may satisfy some simple use-cases the robust and highly unpredictable APIs from the BlackBerry 10 Cryptography Library may be what you really need to give you more fine grained control.

Using the BlackBerry 10 Cryptography Library

So, let’s take a look at how to generate random numbers using this library. Let’s look at the user interface first. The UI is fairly functional with a few buttons at the top and a logging area at the bottom (these screen shots were taken on a Passport device). We’re interested only in the top line of buttons in this post that deal with random number generation – we’ll talk about the others in later posts.

crypto1

When you launch the application you’ll see the screenshot on the left above. The first task is to initialise the RNG by pressing the “Init Random” button. In the screenshot you’ll see that there’s been some activity after we’ve done this – six Cryptographic API functions, all starting “hu_…” have been called.

crypto2

To generate a random number press the “Get Number” button. In the screenshot above on the left you’ll see that a new 32 bit signed random number is generated each time we press this button as a result of a call to hu_RngGetBytes(). The screenshot above on the right just shows the activity after we press: “End Random” to de-initialise the RNG.

The take-home message here is that there is much more work to be done in initialising the RNG than actually calling it to obtain a random number.

Let’s look at the code itself.

The Code

We’ll start with the initialisation step. You can find the code fragment in the image below in GitHub here if you want to look at the source itself or want to copy the fragment for your own use. The macro _CHECKRC() is simply a convenience to process the return code from the cryptographic calls and log them to the application’s screen. A successful return code will have the value: SB_SUCCESS.

crypto3

There are two key objects that the initialisation step must create. These are:

  • _sbCtx – an instance of sb_GlobalCtx (Global Context), and;
  • _rngCtx – an instance of sb_RNGCtx (Random Number Generator Context)

The global context structure is passed to every Security Builder Crypto function and is used to store call-back functions and other global workspace data.

I’ve used hu_GlobalCtxCreateDefault()to create a Global Context. It’s the very first thing you have to do whenever you use the Cryptographic Libraries.

The next four calls to the API are concerned with setting up the details of the algorithms we want to use and the RNG we want to create:

  • hu_registerSbg56() – this enables support for all algorithms from the GSE56 software provider; that is the BlackBerry Cryptographic Kernel version 5.6 (SB-GSE-56).
  • hu_RegisterSystemSeed() – this function simply enables the hu_SeedGet() function to be called at a later time.
  • hu_InitSbg56() – this Initialises the GSE56 provider and performs a series of self-tests to ensure its integrity. It should only be called once so I check to see if it’s been called already earlier in the lifetime of the application.
  • hu_SeedGet() – this generates an initial seed for use by the RNG we’re in the process of setting up. Unpredictability is the key and the seed is generally generated in a way that uses local sources of entropy in the device.

Once the preparation work for the RNG has all been done the hu_RngCreate() function is used to create _rngCtx as an instance of sb_RNGCtx.

Only now with a suitable _sbCtx and _rngCtx are we ready to start generating random numbers. In fact generating the random numbers themselves is a bit of an anti-climax.

crypto4

All you do is call hu_RngGetBytes() with a target – in this case an integer buffer – that will be filled with a random string of bytes. As you can see it’s necessary to pass both _sbCtx and _rngCtx to this function.

You can find the code fragment in the image above in GitHub here if you want to look at the source itself or want to copy the fragment for your own use.

Once you’re finished you need to de-allocate any memory and resources that are associated with the contexts: _sbCtx and _rngCtx, like this:

crypto5

Destroy the contexts in the reverse order in which they were created originally using: hu_RngDestroy() and hu_GlobalCtxDestroy() respectively for the RNG and Global contexts.

You can find the code fragment in the image above in GitHub here if you want to look at the source itself or want to copy the fragment for your own use.

That’s all there is to it.

Summary

I’ve released v1.0.0 of the CryptoSample sample application containing the features described in this article and so you can download, review and reuse the full source code – you can find the URL in the “Resources” section below. I hope this has been interesting and will help set you on your way developing real-world Bluetooth applications for Blackberry 10.

Please feel free to contact me, @jcmrim, via Twitter if you need any help on anything related to this article.

I’ll follow this article with two more covering the topics of Hashes and RSA.

Resources

BlackBerry 10 Cryptography Library APIs

https://github.com/blackberry/Cascades-Community-Samples/tree/master/cryptosample

https://github.com/blackberry/Cascades-Community-Samples/tree/master/AESCryptoDemo

Contacts

John Murray – @jcmrim

BlackBerry

About BlackBerry

BlackBerry is an enterprise software and services company focused on securing and managing IoT endpoints.