Starting from API version 12, lightweight smart wearable devices support operations related to obtaining random numbers.
Random numbers are used to generate temporary session keys and asymmetric encryption algorithm keys. In encryption and decryption, a secure random number generator must feature randomness, unrepeatability, and unpredictability. The random numbers generated by the system meet the requirements of cryptography security pseudo-randomness.
You can call APIs to:
Generate a secure random number of the specified length and uses it to generate a key.
Generate a series of random sequences based on a seed.
It will be helpful if you have basic knowledge of encryption and decryption and understand the following basic concepts:
Internal state
A value in the random number generator memory. The same internal state produces a random number of the same sequence.
Random seed
A number used to initialize the internal state of a pseudorandom number generator. The random number generator generates a series of random sequences based on the seeds.
In the OpenSSL implementation, the internal state of the random number generator changes continuously. Therefore, the generated random number sequences are different even if the same seed is used.
The random number generation algorithm uses the RAND_priv_bytes interface of OpenSSL to generate secure random numbers.
| Algorithm | Length (Byte) |
|---|---|
| CTR_DRBG | [1, INT_MAX] |
Call cryptoFramework.createRandom to create a Random instance.
(Optional) Call Random.setSeed to set a seed for the random number generation pool.
Call Random.generateRandom or Random.generateRandomSync to generate a secure random number.
The length of the random number to generate ranges from 1 to INT_MAX, in bytes.
Return the result using await:
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { BusinessError } from '@kit.BasicServicesKit';
async function doRand() {
try {
let rand = cryptoFramework.createRandom();
let seed = new Uint8Array([1, 2, 3]);
rand.setSeed({ data: seed });
let len = 12;
let randOutput = await rand.generateRandom(len);
console.info('rand output: ' + randOutput.data);
} catch (err) {
let e: BusinessError = err as BusinessError;
console.error(`call failed: errCode: ${e.code}, errMsg: ${e.message}`);
}
} Return the result synchronously:
import { cryptoFramework } from '@kit.CryptoArchitectureKit';
import { BusinessError } from '@kit.BasicServicesKit';
function doRandBySync() {
let rand = cryptoFramework.createRandom();
let len = 24; // Generate a 24-byte random number.
try {
let randData = rand.generateRandomSync(len);
if (randData.data.length !== 0) {
console.info('[Sync]: rand result: ' + randData.data);
} else {
console.error('[Sync]: get rand result: fail!');
}
} catch (error) {
let e: BusinessError = error as BusinessError;
console.error(`do rand failed: errCode: ${e.code}, message: ${e.message}`);
}
}