kanzenminarai / rcg

Random Character Generator
BSD Zero Clause License
13 stars 6 forks source link

use getrandom(2) to securely generate random numbers #13

Closed user21944 closed 1 year ago

user21944 commented 1 year ago

As discussed in #12, this is a more secure method of generating random numbers while also being relatively simple and not requiring any dependencies

user21944 commented 1 year ago

The way getrandom() works is that it simply fills a buffer with the requested number of random bytes as opposed to actually returning a number.

In order to actually get a number, we first pass an integer array as our buffer to getrandom(), and then read off each integer one by one. You could call getrandom() every single time you generate a number, however this would be needlessly slow as syscalls can be quite expensive, which is why the array has been made large enough to store several integers. Each time we call our function, it simply increments an internal pointer and returns the next array element (only calling getrandom() and resetting the pointer once we reach the end of the array).

kanzenminarai commented 1 year ago

By the way, you can add me on discord (kanzentaiwa) if you want to have a better discussion about the source code, and I will need your opinion about some things here.