diff options
| author | Scott Shawcroft <scott.shawcroft@gmail.com> | 2017-06-27 17:37:24 -0700 |
|---|---|---|
| committer | Scott Shawcroft <scott.shawcroft@gmail.com> | 2017-06-27 17:37:24 -0700 |
| commit | a0058e67124b93eb1c8c9c610f823396a7ff7e68 (patch) | |
| tree | 07f6e65722d34c6f29379b9ffe62ea3798471b61 /shared-bindings/os | |
| parent | 265d5dab05f435ab502303e68b6b61adfd03c870 (diff) | |
Introduce a random module that is a subset of CPython's random. It
also initializes in the same way where it takes from a true random
source when available through os.urandom(). After initializing, it
produces deterministic results until the seed is set.
This replaces urandom!
Fixes #139.
Diffstat (limited to 'shared-bindings/os')
| -rw-r--r-- | shared-bindings/os/__init__.c | 17 | ||||
| -rw-r--r-- | shared-bindings/os/__init__.h | 3 |
2 files changed, 20 insertions, 0 deletions
diff --git a/shared-bindings/os/__init__.c b/shared-bindings/os/__init__.c index 6185f0bf2..277224538 100644 --- a/shared-bindings/os/__init__.c +++ b/shared-bindings/os/__init__.c @@ -33,6 +33,7 @@ #include "lib/oofatfs/diskio.h" #include "py/mpstate.h" #include "py/obj.h" +#include "py/runtime.h" #include "shared-bindings/os/__init__.h" //| :mod:`os` --- functions that an OS normally provides @@ -187,6 +188,20 @@ STATIC mp_obj_t os_sync(void) { } MP_DEFINE_CONST_FUN_OBJ_0(os_sync_obj, os_sync); +//| .. function:: urandom(size) +//| +//| Returns a string of *size* random bytes based on a hardware True Random +//| Number Generator. When not available, it will raise a NotImplementedError. +//| +STATIC mp_obj_t os_urandom(mp_obj_t size_in) { + mp_int_t size = mp_obj_get_int(size_in); + uint8_t tmp[size]; + if (!common_hal_os_urandom(tmp, size)) { + mp_raise_NotImplementedError(""); + } + return mp_obj_new_bytes(tmp, size); +} +MP_DEFINE_CONST_FUN_OBJ_1(os_urandom_obj, os_urandom); STATIC const mp_rom_map_elem_t os_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR___name__), MP_OBJ_NEW_QSTR(MP_QSTR_os) }, @@ -206,6 +221,8 @@ STATIC const mp_rom_map_elem_t os_module_globals_table[] = { { MP_OBJ_NEW_QSTR(MP_QSTR_sync), MP_ROM_PTR(&os_sync_obj) }, + { MP_OBJ_NEW_QSTR(MP_QSTR_urandom), MP_ROM_PTR(&os_urandom_obj) }, + //| .. data:: sep //| //| Separator used to dileneate path components such as folder and file names. diff --git a/shared-bindings/os/__init__.h b/shared-bindings/os/__init__.h index e04a39319..41715e7ac 100644 --- a/shared-bindings/os/__init__.h +++ b/shared-bindings/os/__init__.h @@ -45,4 +45,7 @@ void common_hal_os_rmdir(const char* path); mp_obj_t common_hal_os_stat(const char* path); mp_obj_t common_hal_os_statvfs(const char* path); +// Returns true if data was correctly sourced from a true random number generator. +bool common_hal_os_urandom(uint8_t* buffer, mp_uint_t length); + #endif // __MICROPY_INCLUDED_SHARED_BINDINGS_OS___INIT___H__ |
