# Random Number Generation 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 random number of the specified length and uses it to generate a key. - Generate a series of random sequences based on the specified 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. ## Supported Algorithms and Specifications The random number generation algorithm uses the **RAND_priv_bytes** interface of OpenSSL to generate random numbers. | Algorithm| Length (Byte)| | -------- | -------- | | CTR_DRBG | [1, INT_MAX] | ## How to Develop 1. Use [cryptoFramework.createRandom](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreaterandom) to create a **Random** instance. 2. Use [Random.setSeed](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#setseed) to set a seed for the random number generation pool. 3. Use [Random.generateRandom](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generaterandom) to generate a random number based on the specified byte length. The byte length ranges from **1** to **INT_MAX**. - Return the result using **await**: ```ts import cryptoFramework from '@ohos.security.cryptoFramework'; async function doRand() { 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); } ``` - Return the result synchronously: ```ts import cryptoFramework from '@ohos.security.cryptoFramework'; import { BusinessError } from '@ohos.base'; function doRandBySync() { let rand = cryptoFramework.createRandom(); let len = 24; // Generate a 24-byte random number. try { let randData = rand.generateRandomSync(len); if (randData != null) { 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, ${e.code}, ${e.message}`); } } ```