Secure Random Number Generation
Note:
Currently in the beta phase.
Random numbers are primarily used in scenarios such as temporary session key generation and asymmetric encryption key generation. In cryptographic contexts, secure random number generators must possess randomness, unpredictability, and non-repeatability. The random numbers generated by the current system meet the requirements of cryptographically secure pseudorandomness.
Developers can call APIs to achieve the following functionalities:
- Generate secure random numbers of specified lengths for corresponding key generation.
- Specify random seeds to generate sequences of random numbers.
Before development, developers should have a basic understanding of cryptography fundamentals and be familiar with the following key concepts related to random numbers:
-
Internal State
Represents the numerical values in the memory of the random number generator. When the internal state is the same, the random number generator will produce a fixed sequence of random numbers.
-
Random Seed
Data used to initialize the internal state of a pseudorandom number generator. The random number generator uses the seed to generate a sequence of random numbers.
In the current OpenSSL implementation, the internal state of the random number generator continuously changes. Even if the same seed is set, the generated random number sequence will differ.
Supported Algorithms and Specifications
The random number generation algorithm uses OpenSSL's RAND_priv_bytes interface to generate secure random numbers.
| Algorithm | Length (Byte) |
|---|---|
| CTR_DRBG | [1, INT_MAX] |
Development Steps
-
Call
createRandomto create a random number instance. -
(Optional) Set
DataBlobdata and callsetSeedto seed the random number generation pool. -
Specify the byte length and call
generateRandomto generate a secure random number.The specified byte length must be within the range of 1 to
INT_MAX.
Example
The following demonstrates the synchronous method:
import kit.CryptoArchitectureKit.*
import ohos.hilog.Hilog
import ohos.business_exception.BusinessException
func doRand() {
let rand = createRandom()
let len: Int32 = 24 // Generate a 24-byte random number.
try {
let randData = rand.generateRandom(len)
Hilog.info(0,"","rand result: ${randData.data}")
} catch (e: BusinessException) {
Hilog.error(0,"","do rand failed, ${e.code}, ${e.message}")
}
}