• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Generating Secure Random Numbers (ArkTS)
2
3<!--Kit: Crypto Architecture Kit-->
4<!--Subsystem: Security-->
5<!--Owner: @zxz--3-->
6<!--Designer: @lanming-->
7<!--Tester: @PAFT-->
8<!--Adviser: @zengyawen-->
9
10> **NOTE**
11>
12> Since API version 12, wearable devices support operations related to obtaining random numbers.
13
14Random 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.
15
16You can call APIs to:
17
18- Generate a secure random number of the specified length and uses it to generate a key.
19
20- Generate a series of random sequences based on a seed.
21
22It will be helpful if you have basic knowledge of encryption and decryption and understand the following basic concepts:
23
24- Internal state
25
26  A value in the random number generator memory. The same internal state produces a random number of the same sequence.
27
28- Random seed
29
30  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.
31
32  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.
33
34## Supported Algorithms and Specifications
35
36The random number generation algorithm uses the **RAND_priv_bytes** interface of OpenSSL to generate secure random numbers.
37
38| Algorithm| Length (Byte)|
39| -------- | -------- |
40| CTR_DRBG | [1, INT_MAX] |
41
42## How to Develop
43
441. Call [cryptoFramework.createRandom](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#cryptoframeworkcreaterandom) to create a **Random** instance.
45
462. (Optional) Call [Random.setSeed](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#setseed) to set a seed for the random number generation pool.
47
483. Call [Random.generateRandom](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generaterandom) or [Random.generateRandomSync](../../reference/apis-crypto-architecture-kit/js-apis-cryptoFramework.md#generaterandomsync10) to generate a secure random number.
49
50   The length of the random number to generate ranges from **1** to **INT_MAX**, in bytes.
51
52- Return the result using **await**:
53  ```ts
54  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
55
56  async function doRand() {
57    let rand = cryptoFramework.createRandom();
58    let seed = new Uint8Array([1, 2, 3]);
59    rand.setSeed({ data: seed });
60    let len = 12;
61    let randOutput = await rand.generateRandom(len);
62    console.info('rand output:' + randOutput.data);
63  }
64  ```
65
66- Return the result synchronously:
67  ```ts
68  import { cryptoFramework } from '@kit.CryptoArchitectureKit';
69  import { BusinessError } from '@kit.BasicServicesKit';
70
71  function doRandBySync() {
72    let rand = cryptoFramework.createRandom();
73    let len = 24; // Generate a 24-byte random number.
74    try {
75      let randData = rand.generateRandomSync(len);
76      if (randData !== null) {
77        console.info("[Sync]: rand result: " + randData.data);
78      } else {
79        console.error("[Sync]: get rand result fail!");
80      }
81    } catch (error) {
82      let e: BusinessError = error as BusinessError;
83      console.error(`do rand failed, ${e.code}, ${e.message}`);
84    }
85  }
86  ```
87