Click here to Skip to main content
15,886,780 members
Articles / Mobile Apps / Android
Article

Sample Code: Random Number Application

Rate me:
Please Sign up or sign in to vote.
3.86/5 (4 votes)
18 Sep 2014CPOL4 min read 11.4K   10  
This paper provides an overview of random number APIs and also shows how to use different APIs to generate random numbers on the Android* OS.

This article is for our sponsors at CodeProject. These articles are intended to provide you with information on products and services that we consider useful and of value to developers

Introduction

A Random Number Generator (RNG) is a utility or device of some type that produces a sequence of numbers on an interval such that values appear unpredictable. An RNG is an indispensable component of information security applications. In fact, a cryptographic protocol may have considerable robustness but suffer from widespread attack due to weak key generation methods underlying it. The hardware-assisted RNG can be used to fix this weakness, thus significantly increasing cryptographic robustness.

This paper provides an overview of random number APIs and also shows how to use different APIs to generate random numbers on the Android* OS.

We recommend that you try out the features and compile the code as you read through the paper.

Image 1

Code and Explanations

There are four different ways to generate random numbers in Android.

  • java.util.random
  • java.security.SecureRandom
  • /dev/urandom
  • OpenSSL* API

However, if you are using an RNG to generate a cryptographic key for protecting your data, the typical Random class is known to be easier to crack and should not be used. The other three approaches should provide strong keys.

java.util.random

Using Java* Random Number API is very straightforward. A call to Random.nextInt() will return a 4-byte random value ( with 2^32 possible values). This API works well for cases where you don’t rely on truly random numbers.

C++
for (int i = 0; i < lastVal; i += 2) {
    dataRandomPoints[i] = (rand.nextInt() % widget_width);
    dataRandomPoints[i+1] = (rand.nextInt() % widget_height);

}

java.security.SecureRandom

SecureRandom resembles java.util.Random in that you can make a SecureRandom.nextInt() call to return a 4-byte random value. SecureRandom is cryptographically strong, although developers should be aware of recent recommendations that they seed SecureRandom with bytes from /dev/urandom before generating random numbers. The example below does not seed from /dev/urandom.

C++
SecureRandom srand = new SecureRandom();
shouldDraw = (srand.nextInt() % randomMod );

/dev/urandom

Linux* operating systems (Android included) have a special file created by the kernel that can feed random numbers to applications. The slowest of the four implementations, it generates cryptographically safe high-entropy values by incorporating noise from parts of the operating system (e.g., device drivers) into the RNG. We can get the random number directly from the kernel level by reading from the /dev/urandom file. /dev/urandom will access the hardware-assisted RNG if it is available.

C++
unsigned int cKeyBuffer[keysize];
memset(cKeyBuffer, 0, sizeof(unsigned int) * keysize);

FILE *fin;
strcpy(filein, "/dev/urandom");
fin = fopen(filein, "rb");

if (fin != NULL) {
    fread(cKeyBuffer, sizeof(int), keysize, fin);
    fclose (fin);
}

OpenSSL API

We also can use OpenSSL API to get random numbers in native (C) code. You can see that OpenSSL can be seeded with bytes from /dev/urandom and then can be used to generate cryptographically secure random numbers. OpenSSL API will access the hardware-assisted RNG if it is available.

C++
int seedbytes = 1024;
unsigned int cKeyBuffer[keysize];
memset(cKeyBuffer, 0, sizeof(unsigned int) * keysize);

if (!opensslIsSeeded) {

    if (!RAND_load_file("/dev/urandom", seedbytes)) {
        __android_log_print(ANDROID_LOG_ERROR, TAG, "Failed to seed OpenSSL RNG");
        return jKeyBuffer;
    }

    opensslIsSeeded = 1;
}

if (!RAND_bytes((unsigned char *)cKeyBuffer, keysize * sizeof(int))) {
    __android_log_print(ANDROID_LOG_ERROR, TAG, "Faled to create OpenSSSL random integers: %ul", ERR_get_error);
}

Conclusion

By implementing code like the samples described in this paper, you can quickly learn how to use four different ways to generate random numbers.

Related Articles and Resources:

Notices

INFORMATION IN THIS DOCUMENT IS PROVIDED IN CONNECTION WITH INTEL PRODUCTS. NO LICENSE, EXPRESS OR IMPLIED, BY ESTOPPEL OR OTHERWISE, TO ANY INTELLECTUAL PROPERTY RIGHTS IS GRANTED BY THIS DOCUMENT. EXCEPT AS PROVIDED IN INTEL'S TERMS AND CONDITIONS OF SALE FOR SUCH PRODUCTS, INTEL ASSUMES NO LIABILITY WHATSOEVER AND INTEL DISCLAIMS ANY EXPRESS OR IMPLIED WARRANTY, RELATING TO SALE AND/OR USE OF INTEL PRODUCTS INCLUDING LIABILITY OR WARRANTIES RELATING TO FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABILITY, OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.

UNLESS OTHERWISE AGREED IN WRITING BY INTEL, THE INTEL PRODUCTS ARE NOT DESIGNED NOR INTENDED FOR ANY APPLICATION IN WHICH THE FAILURE OF THE INTEL PRODUCT COULD CREATE A SITUATION WHERE PERSONAL INJURY OR DEATH MAY OCCUR.

Intel may make changes to specifications and product descriptions at any time, without notice. Designers must not rely on the absence or characteristics of any features or instructions marked "reserved" or "undefined." Intel reserves these for future definition and shall have no responsibility whatsoever for conflicts or incompatibilities arising from future changes to them. The information here is subject to change without notice. Do not finalize a design with this information.

The products described in this document may contain design defects or errors known as errata which may cause the product to deviate from published specifications. Current characterized errata are available on request.

Contact your local Intel sales office or your distributor to obtain the latest specifications and before placing your product order.

Copies of documents which have an order number and are referenced in this document, or other Intel literature, may be obtained by calling 1-800-548-4725, or go to: http://www.intel.com/design/literature.htm

Software and workloads used in performance tests may have been optimized for performance only on Intel microprocessors. Performance tests, such as SYSmark* and MobileMark*, are measured using specific computer systems, components, software, operations, and functions. Any change to any of those factors may cause the results to vary. You should consult other information and performance tests to assist you in fully evaluating your contemplated purchases, including the performance of that product when combined with other products.

Any software source code reprinted in this document is furnished under a software license and may only be used or copied in accordance with the terms of that license.

Intel, the Intel logo, and Atom are trademarks of Intel Corporation in the US and/or other countries.

Copyright © 2014 Intel Corporation. All rights reserved.

*Other names and brands may be claimed as the property of others.

To learn more about Intel tools for the Android developer, visit Intel® Developer Zone for Android.

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


Written By
United States United States
Intel is inside more and more Android devices, and we have tools and resources to make your app development faster and easier.


Comments and Discussions