The core value of this group is to bring developers up to speed with BB technology, concentrating on BB10.Exploring efficiency, beauty and power BlackBerry provides to its users by designing Apps that can be used globally and that improves developers life as it improves community life.
Last month I discussed the BlackBerry Tools for Android Development SDK and how we can troubleshoot Android Install Error Codes using the BlackBerry Deploy tool via the PackageManager Class within the AOSP source code. This month, let’s continue our discussion around the SDK and learn how we can manually edit our manifest file for BlackBerry 10 without requiring access to our project’s source code.
This process can be used to adjust various entries within a manifest, such as setting a custom Application-Version value or adding the _sys_use_consumer_push signing permission when creating push-enabled Android apps on BlackBerry 10.
The BlackBerry APK Packager Tool
Our tool of choice for this task will be the BlackBerry APK Packager, which as you can probably guess, packages the APK file (Android application package) into the BAR file format for BlackBerry 10. I’m a big fan of this tool because once set up, its ease-of-use allows most apps to be repackaged within about 10 seconds. All that’s required is to browse to the APK file of choice (release builds only please), click a Package button, and provide the BlackBerry signing password. The toolset builds the BAR file (BlackBerry archive) from there and results in a release-signed BAR file for distribution via BlackBerry World, or by sideloading it over USB/Wi-Fi.
Android BAR File Structure
Within the newly created BAR file, the toolset actually leaves the APK file intact while adding some additional files to account for the app running on a BlackBerry 10 device. The new BAR file has two main directories within it:
The META-INF folder contains the new manifest named MANIFEST.MF based upon the AndroidManifest.xml file within the APK, and four (4) BlackBerry signature files (AUTHOR/RDK) to be verified upon installing the app.
The android folder contains the APK file, in addition to a res subfolder containing the various app icons you’ve included
Upon installation, the BlackBerry 10 OS will install the APK file and its associated Dalvik executables (DEX files) directly to the BlackBerry Runtime for Android apps, while taking the associated meta information and appropriate app icon from the BAR file. The installer process also verifies both the Android and BlackBerry signatures to ensure they’re intact and valid.
Adjusting the Manifest File
When it comes to editing values within our MANIFEST.MF file, we can use any standard text editor to make and save our changes.
1. Repackage the APK using the BlackBerry APK Packager tool
Provide the location of the APK file
Select the Package button (you don’t need to sign the BAR yet, but doing so won’t hinder what we are trying to accomplish)
2. Extract the MANIFEST.MF file
Within your archive editor of choice, open the newly packaged BAR file
Navigate to the META-INF folder, and save the MANIFEST.MF file to a convenient location on your development machine
Feel free to change the filename to avoid confusion, if you see fit, keeping the *.MF file extension
Close the archive editor (no need to save any changes to the BAR file itself if prompted to)
3. Edit the MANIFEST.MF file
Within your favorite text editor, open the MANIFEST.MF file (or whatever you may have changed the filename to) which was saved in step 2 above
Make the necessary changes to the entries within the body of the manifest’s text
Save the changes and close the text editor
4. Repackage the APK file, again, to include the custom manifest file
Open the BlackBerry APK Package tool
Provide the location of the APK file (should be the same as step 1 above)
Expand the Advanced Settings option
Within the Custom Manifest field, provide the location of the edited manifest file from step 3 above
Select the Add Custom Manifest Values (merge) checkbox
Select the Sign checkbox
Select the Package button
Provide your BlackBerry signing password when prompted (or walk through the Configure Signing process if you haven’t signed a BAR file before)
5. Verify The Changes
Just as we did in step 2 above, within your archive editor of choice, open the newly packaged BAR file
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:
It demonstrates three common cryptography use-cases using the BlackBerry 10 Cryptography Library APIs:
Generating a simple random number;
Calculating Hashes (SHA1, SHA256) and HMAC using a predefined key;
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:
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!
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.
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.
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.
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.
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.
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:
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.
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.
The Secure Work Space (SWS) for BlackBerry Enterprise Service 12 (BES12) provides an ideal solution for compartmentalizing applications between work and personal usage. In addition to the integrated enterprise-level applications such as email, calendar, and web browser, the user can also install third-party applications through secure wrapping. The applications installed on the work space contain data that cannot be accessed on the personal side, which is useful for keeping client information confidential and secure.
One core application that is missing from the packaged suite is a native camera app that is dedicated to the work space. With built-in cameras on all modern day smartphones, it is easy for customers to send digital media amongst one another whether it’s for sharing documents or previewing prototypes. Regardless, from a security standpoint many companies still experience leaks of confidential information through media transfer. This is why it is paramount to have a native camera application in the Secure Work Space which will encrypt captured files and render them inaccessible from the personal side, minimizing the risk of tampering and misuse.
Many third-party camera apps will work on the Secure Work Space as long as their APK’s (Android application package) are properly signed and wrapped. However, some of them are incompatible with the SWS encryption and will merely save a copy of the media files on the personal side. Others will simply fail at attaching the media files onto the work space and basically double as a secondary personal camera. In order to leverage the advantages of the SWS without the advertisements and unnecessary features that often come with third-party apps, it is best to create a custom camera app from the ground up. Fortunately, the Android Developer pages contain comprehensive demos and detailed instructions to build some of the basic components of the platform, including the camera. It is important to develop a customized camera feature rather than invoke the native camera app as the latter already resides in the personal side. Creating the camera app is simply a matter of making a few small changes to Android’s existing sample code and wrapping it for the SWS.
Building a Secure Camera App
Thanks to Android’s open-source agreement, we do not need to reinvent the wheel as there are already samples we can use to build the camera app.
1. Open Android Studio (recommended) or Eclipse and create a new Android project.
2. In the AndroidManifest.xml, add the following tags under <manifest> to ensure your application has the proper hardware permissions:
3. Visit the Camera Developer guide and copy and paste the sample code under Building a Camera App subsection in your MainActivity.java file.
4. Follow the detailed instructions on creating a preview class, building a preview layout, and finally capturing and saving the files on the device.
When it comes to identifying where the captured files should reside, make sure that the variable mediaStorageDir points to DIRECTORY_DCIM, the default location for all Digital Camera Images.
5. Create an XML layout for the camera preview by copying the layout code provided in the sample. This will display the user interface controls for taking a picture.
6. Remember to release the camera every time it is not being used in the onPause() method in order for other applications to invoke the camera in the future.
Broadcasting Media Intent
A very important feature that allows this application to be compatible with the Secure Work Space is its ability to display the captured images in the Shared Media Folder. To enable this feature, one must broadcast the ACTION_MEDIA_SCANNER_SCAN_FILE intent. Simply add the following function to the MainActivity class and call it from the PictureCallback:
This allows the saved images to be stored in the native media gallery, which includes the Shared Media Folder in the SWS.
After building this app and retrieving the signed APK file, it can then be wrapped and deployed from the BES to be used for the Secure Work Space. You should now be able to take photos in the work side and share them securely without the images being visible on the personal side. For the complete Android project, please refer to the Secure-Work-Space subfolder on BlackBerry’s Github.