Embedded SDK
Embedded SDK
Loading...
Searching...
No Matches
cx_rng.c
Go to the documentation of this file.
1
2/*******************************************************************************
3 * Ledger Nano S - Secure firmware
4 * (c) 2022 Ledger
5 *
6 * Licensed under the Apache License, Version 2.0 (the "License");
7 * you may not use this file except in compliance with the License.
8 * You may obtain a copy of the License at
9 *
10 * http://www.apache.org/licenses/LICENSE-2.0
11 *
12 * Unless required by applicable law or agreed to in writing, software
13 * distributed under the License is distributed on an "AS IS" BASIS,
14 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 * See the License for the specific language governing permissions and
16 * limitations under the License.
17 ********************************************************************************/
18
19#include "app_config.h"
20
21#ifdef HAVE_RNG
22
23#include "cx_ram.h"
24#include "cx_utils.h"
25#include "cx_crc.h"
26#include "lcx_rng.h"
27#include "errors.h"
28#include "exceptions.h"
29
30#include "os_halt.h"
31#include "os_math.h"
32#include "os_random.h"
33#include <string.h>
34
35void cx_rng_no_throw(uint8_t *buffer, size_t len)
36{
37 cx_err_t error;
38
39 error = cx_get_random_bytes(buffer, len);
40 if (error) {
41 /* XXX: calling halt() add a dependency to THROW (os_longjmp). */
42 while (1)
43 ;
44 }
45}
46
47uint32_t cx_rng_u32_range_func(uint32_t a, uint32_t b, cx_rng_u32_range_randfunc_t randfunc)
48{
49 uint32_t range = b - a;
50 uint32_t r;
51
52 if ((range & (range - 1)) == 0) { // special case: range is a power of 2
53 r = randfunc();
54 return a + r % range;
55 }
56
57 uint32_t chunk_size = UINT32_MAX / range;
58 uint32_t last_chunk_value = chunk_size * range;
59 r = randfunc();
60 while (r >= last_chunk_value) {
61 r = randfunc();
62 }
63 return a + r / chunk_size;
64}
65
66#endif // HAVE_RNG
Random Number Generation.
unsigned char uint8_t
Definition usbd_conf.h:53