xref: /freebsd/crypto/libecc/src/utils/utils_rand.c (revision f0865ec9906d5a18fa2a3b61381f22ce16e606ad)
1*f0865ec9SKyle Evans /*
2*f0865ec9SKyle Evans  *  Copyright (C) 2023 - This file is part of libecc project
3*f0865ec9SKyle Evans  *
4*f0865ec9SKyle Evans  *  Authors:
5*f0865ec9SKyle Evans  *      Ryad BENADJILA <ryadbenadjila@gmail.com>
6*f0865ec9SKyle Evans  *      Arnaud EBALARD <arnaud.ebalard@ssi.gouv.fr>
7*f0865ec9SKyle Evans  *
8*f0865ec9SKyle Evans  *  This software is licensed under a dual BSD and GPL v2 license.
9*f0865ec9SKyle Evans  *  See LICENSE file at the root folder of the project.
10*f0865ec9SKyle Evans  */
11*f0865ec9SKyle Evans #include <libecc/utils/utils_rand.h>
12*f0865ec9SKyle Evans 
13*f0865ec9SKyle Evans /* Unsafe random source:
14*f0865ec9SKyle Evans  * Initial seeding is performed using good entropy, then
15*f0865ec9SKyle Evans  * a congruential linear system is used.
16*f0865ec9SKyle Evans  */
17*f0865ec9SKyle Evans static u64 seed = 0;
get_unsafe_random(unsigned char * buf,u16 len)18*f0865ec9SKyle Evans int get_unsafe_random(unsigned char *buf, u16 len)
19*f0865ec9SKyle Evans {
20*f0865ec9SKyle Evans         int ret;
21*f0865ec9SKyle Evans         u64 a, b;
22*f0865ec9SKyle Evans         u16 i, j;
23*f0865ec9SKyle Evans         a = (u64)2862933555777941757;
24*f0865ec9SKyle Evans         b = (u64)3037000493;
25*f0865ec9SKyle Evans 
26*f0865ec9SKyle Evans         if(seed == 0){
27*f0865ec9SKyle Evans                 ret = get_random((u8*)&seed, sizeof(seed));
28*f0865ec9SKyle Evans                 if(ret){
29*f0865ec9SKyle Evans                         ret = -1;
30*f0865ec9SKyle Evans                         goto err;
31*f0865ec9SKyle Evans                 }
32*f0865ec9SKyle Evans         }
33*f0865ec9SKyle Evans 
34*f0865ec9SKyle Evans         i = 0;
35*f0865ec9SKyle Evans         while(i < len){
36*f0865ec9SKyle Evans                 /* Use a congruential linear generator */
37*f0865ec9SKyle Evans                 seed = ((a * seed) + b);
38*f0865ec9SKyle Evans 
39*f0865ec9SKyle Evans                 for(j = 0; j < sizeof(seed); j++){
40*f0865ec9SKyle Evans                         if((i + j) < len){
41*f0865ec9SKyle Evans                                 buf[i + j] = (u8)((seed >> (j * 8)) & 0xff);
42*f0865ec9SKyle Evans                         }
43*f0865ec9SKyle Evans                 }
44*f0865ec9SKyle Evans                 i = (u16)(i + sizeof(seed));
45*f0865ec9SKyle Evans         }
46*f0865ec9SKyle Evans 
47*f0865ec9SKyle Evans         ret = 0;
48*f0865ec9SKyle Evans 
49*f0865ec9SKyle Evans err:
50*f0865ec9SKyle Evans         return ret;
51*f0865ec9SKyle Evans }
52