Skip to content

Commit c6cb082

Browse files
committed
alif/mpconfigport: Enable os.urandom().
Uses the SE services to provide random numbers. Signed-off-by: Damien George <damien@micropython.org>
1 parent 4e62ade commit c6cb082

2 files changed

Lines changed: 51 additions & 0 deletions

File tree

ports/alif/modos.c

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,49 @@
1+
/*
2+
* This file is part of the MicroPython project, http://micropython.org/
3+
*
4+
* The MIT License (MIT)
5+
*
6+
* Copyright (c) 2024 OpenMV LLC.
7+
*
8+
* Permission is hereby granted, free of charge, to any person obtaining a copy
9+
* of this software and associated documentation files (the "Software"), to deal
10+
* in the Software without restriction, including without limitation the rights
11+
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
12+
* copies of the Software, and to permit persons to whom the Software is
13+
* furnished to do so, subject to the following conditions:
14+
*
15+
* The above copyright notice and this permission notice shall be included in
16+
* all copies or substantial portions of the Software.
17+
*
18+
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
19+
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
20+
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
21+
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
22+
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
23+
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
24+
* THE SOFTWARE.
25+
*/
26+
27+
#include "py/runtime.h"
28+
#include "se_services.h"
29+
30+
#if MICROPY_PY_OS_URANDOM
31+
static mp_obj_t mp_os_urandom(mp_obj_t num) {
32+
mp_int_t n = mp_obj_get_int(num);
33+
vstr_t vstr;
34+
vstr_init_len(&vstr, n);
35+
uint64_t rnd = 0;
36+
size_t rnd_bits = 0;
37+
for (int i = 0; i < n; i++) {
38+
if (rnd_bits == 0) {
39+
rnd = se_services_rand64();
40+
rnd_bits = 64;
41+
}
42+
vstr.buf[i] = rnd;
43+
rnd >>= 8;
44+
rnd_bits -= 8;
45+
}
46+
return mp_obj_new_bytes_from_vstr(&vstr);
47+
}
48+
static MP_DEFINE_CONST_FUN_OBJ_1(mp_os_urandom_obj, mp_os_urandom);
49+
#endif

ports/alif/mpconfigport.h

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -87,10 +87,12 @@
8787

8888
// Extended modules
8989
#define MICROPY_EPOCH_IS_1970 (1)
90+
#define MICROPY_PY_OS_INCLUDEFILE "ports/alif/modos.c"
9091
#define MICROPY_PY_OS_DUPTERM (1)
9192
#define MICROPY_PY_OS_SEP (1)
9293
#define MICROPY_PY_OS_SYNC (1)
9394
#define MICROPY_PY_OS_UNAME (1)
95+
#define MICROPY_PY_OS_URANDOM (1)
9496
#define MICROPY_PY_TIME (1)
9597
#define MICROPY_PY_MACHINE (1)
9698
#define MICROPY_PY_MACHINE_INCLUDEFILE "ports/alif/modmachine.c"

0 commit comments

Comments
 (0)