random numer generation

This commit is contained in:
2026-09-25 17:18:40 +02:00
parent 700b1ec4b4
commit 3fe3d05b1b
2 changed files with 60 additions and 0 deletions
+52
View File
@@ -0,0 +1,52 @@
#include "kernel.h"
#include <system.h>
#include <types.h>
uint64_t (*get_random_number)();
// this starting value it truly random i have thrown a dice few times
uint64_t LFSR = 61113534451;
// RDSEED may be backdoored by NSA
extern uint64_t rand_rdrand();
asm(".intel_syntax noprefix\n"
".global rand_rdrand\n"
"rand_rdrand:"
" rdrand rax\n"
" ret\n"
".att_syntax prefix\n");
uint64_t rand_software() {
uint64_t lsb = LFSR & 1;
LFSR >>= 1;
if (lsb) {
LFSR ^= 0x800000000000000DULL;
}
return LFSR;
}
void rand_init() {
uint32_t eax = 1, ebx = 0, ecx = 0, edx = 0;
cpuid(&eax, &ebx, &ecx, &edx);
// check for RDRAND
if ((ecx >> 30) & 1) {
get_random_number = rand_rdrand;
} else {
printk("[\e[33mWARNING\e[0m] RDRAND not available falling back "
"to software\n");
// check for RDSEED
if ((ebx >> 18) & 1) {
asm(".intel_syntax noprefix\n"
"rdseed %0\n"
".att_syntax prefix\n"
: "=r"(LFSR));
} else {
printk("[\e[\e[33mWARNING\e[0m] RDSEED not available "
"falling back "
"to developers dice trows\n");
}
get_random_number = rand_software;
}
printk("[\e[32mINFO\e[0m] RNG initialized!\n");
}