2020
2121# pylint: disable=no-member,no-name-in-module
2222
23+ from __future__ import annotations
24+
2325from wolfcrypt ._ffi import ffi as _ffi
2426from wolfcrypt ._ffi import lib as _lib
2527
@@ -31,47 +33,45 @@ class Random:
3133 A Cryptographically Secure Pseudo Random Number Generator - CSPRNG
3234 """
3335
34- def __init__ (self , nonce = _ffi . NULL , device_id = _lib .INVALID_DEVID ):
35- self .native_object = _ffi .new ("WC_RNG *" )
36+ def __init__ (self , nonce : __builtins__ . bytes = b"" , device_id : int = _lib .INVALID_DEVID ) -> None :
37+ self .native_object : _lib . RNG | None = _ffi .new ("WC_RNG *" )
3638
37- if nonce == _ffi .NULL :
38- nonce_size = 0
39- else :
40- nonce_size = len (nonce )
41- ret = _lib .wc_InitRngNonce_ex (self .native_object , nonce , nonce_size , _ffi .NULL , device_id )
39+ ret = _lib .wc_InitRngNonce_ex (self .native_object , nonce , len (nonce ), _ffi .NULL , device_id )
4240 if ret < 0 : # pragma: no cover
4341 self .native_object = None
4442 raise WolfCryptError ("RNG init error (%d)" % ret )
4543
4644 # making sure _lib.wc_FreeRng outlives WC_RNG instances
4745 _delete = _lib .wc_FreeRng
4846
49- def __del__ (self ):
47+ def __del__ (self ) -> None :
5048 if self .native_object :
5149 try :
5250 self ._delete (self .native_object )
5351 except AttributeError :
5452 # Can occur during interpreter shutdown
5553 pass
5654
57- def byte (self ):
55+ def byte (self ) -> __builtins__ . bytes :
5856 """
5957 Generate and return a random byte.
6058 """
61- result = _ffi .new (' byte[1]' )
59+ result = _ffi .new (" byte[1]" )
6260
61+ assert self .native_object is not None
6362 ret = _lib .wc_RNG_GenerateByte (self .native_object , result )
6463 if ret < 0 : # pragma: no cover
6564 raise WolfCryptError ("RNG generate byte error (%d)" % ret )
6665
6766 return _ffi .buffer (result , 1 )[:]
6867
69- def bytes (self , length ) :
68+ def bytes (self , length : int ) -> __builtins__ . bytes :
7069 """
7170 Generate and return a random sequence of length bytes.
7271 """
73- result = _ffi .new (' byte[%d]' % length )
72+ result = _ffi .new (" byte[%d]" % length )
7473
74+ assert self .native_object is not None
7575 ret = _lib .wc_RNG_GenerateBlock (self .native_object , result , length )
7676 if ret < 0 : # pragma: no cover
7777 raise WolfCryptError ("RNG generate block error (%d)" % ret )
0 commit comments