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 <stdint.h>
24#include "lcx_rng.h"
25
26#include "os_random.h"
27
28void cx_rng_no_throw(uint8_t *buffer, size_t len)
29{
30 cx_err_t error;
31
32 error = cx_get_random_bytes(buffer, len);
33 if (error) {
34 /* XXX: calling halt() add a dependency to THROW (os_longjmp). */
35 while (1)
36 ;
37 }
38}
39
40uint32_t cx_rng_u32_range_func(uint32_t a, uint32_t b, cx_rng_u32_range_randfunc_t randfunc)
41{
42 uint32_t range = b - a;
43 uint32_t r;
44
45 if ((range & (range - 1)) == 0) { // special case: range is a power of 2
46 r = randfunc();
47 return a + r % range;
48 }
49
50 uint32_t chunk_size = UINT32_MAX / range;
51 uint32_t last_chunk_value = chunk_size * range;
52 r = randfunc();
53 while (r >= last_chunk_value) {
54 r = randfunc();
55 }
56 return a + r / chunk_size;
57}
58
59#endif // HAVE_RNG
Random Number Generation.