Re: [hackers] [sbase][PATCH] libutil/random: better random seed

2024-03-05 Thread NRK
> - *state = ts.tv_nsec;
> + *state = (intptr_t) ^ time(NULL) ^ (ts.tv_nsec * 0xAC5533CD);

tv_nsec is `long` which is signed. Signed interger overflow is
undefined. You need to cast it to `unsigned long` before multiply:

... ^ ((unsigned long)ts.tv_nsec * 0xAC5533CD)

- NRK



Re: [hackers] [sbase][PATCH] libutil/random: better random seed

2024-03-05 Thread Steve Ward
On Mon, Mar 4, 2024 at 5:03 PM Elie Le Vaillant  wrote:
>
> Thanks NRK
> ---
>  libutil/random.c | 3 ++-
>  1 file changed, 2 insertions(+), 1 deletion(-)
>
> diff --git a/libutil/random.c b/libutil/random.c
> index 780ba29..6b795a9 100644
> --- a/libutil/random.c
> +++ b/libutil/random.c
> @@ -1,4 +1,5 @@
>  #include 
> +#include 
>  #include 
>
>  static uint64_t globalstate;
> @@ -66,7 +67,7 @@ rng32_seed_r(uint64_t *state)
>  {
> struct timespec ts;
> clock_gettime(CLOCK_REALTIME, );
> -   *state = ts.tv_nsec;
> +   *state = (intptr_t) ^ time(NULL) ^ (ts.tv_nsec * 0xAC5533CD);
>  }
>
>  void
> --
> 2.44.0
>
>

Instead of calling time(NULL), you already have the second of the
epoch in ts.tv_sec.



[hackers] [sbase][PATCH] libutil/random: better random seed

2024-03-04 Thread Elie Le Vaillant
Thanks NRK
---
 libutil/random.c | 3 ++-
 1 file changed, 2 insertions(+), 1 deletion(-)

diff --git a/libutil/random.c b/libutil/random.c
index 780ba29..6b795a9 100644
--- a/libutil/random.c
+++ b/libutil/random.c
@@ -1,4 +1,5 @@
 #include 
+#include 
 #include 
 
 static uint64_t globalstate;
@@ -66,7 +67,7 @@ rng32_seed_r(uint64_t *state)
 {
struct timespec ts;
clock_gettime(CLOCK_REALTIME, );
-   *state = ts.tv_nsec;
+   *state = (intptr_t) ^ time(NULL) ^ (ts.tv_nsec * 0xAC5533CD);
 }
 
 void
-- 
2.44.0