Argyle-Software / kyber

A rust implementation of the Kyber post-quantum KEM
https://docs.rs/pqc_kyber/
Apache License 2.0
163 stars 37 forks source link

Error handling for randombytes #86

Closed francescomedina closed 1 year ago

francescomedina commented 1 year ago

Reason:

The rng parameter is very important for the Kyber library since is used in several functions. Compatibility for no_std devices means that the rand::thread_rng() function cannot be used in order to generate the rng parameter. Consequently, it is necessary to implement a proper custom Rng that implements RngCore + CryptoRng and in particular, is very important to be responsible for the correct functioning of the fill_bytes() function in order to avoid errors. Some microcontrollers (like STM32F2xx or STM32F4xx) have already embedded the random number generator peripheral. In case of microcontrollers that do not provide such peripheral, they may assign the rng task to external hardware modules that can be subject to interruptions or malfunctions.

Proposal:

Since randombytes() is a kyber library function that calls the fill_bytes() from RngCore trait, I propose to use try_fill_bytes() (from RngCore trait) since it's safer to use in order to ensure a proper error handling (it returns a Resut<(), Error>) and reporting for devices which can fail (as declared here as well). To be consistent and follow the error pattern used, I’ve added a new type to the KyberErrors enum called RandomBytesGenerator and also I made sure that the error is propagated up to the caller as Decapsulation and InvalidInput errors were also handled. I added kex and kem tests for this variation and modified the readme.md. All tests passed correctly.

FYI @mberry