rsa_arduino/prng.cpp
2024-03-05 14:15:03 +01:00

94 lines
2.0 KiB
C++

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include "prng.h"
#include "constantes.h"
#include <Arduino.h>
/*
* Fill the entropy structure with random data
*/
void init_entropy(){
if (DEBUG)
Serial.println("Generation entropy");
// Generate entropy
int sensorValue = 0;
while(s_entropy.pool_size < BUFSIZE){
generateEntropy(s_entropy.position++);
s_entropy.pool_size++;
// Add a delay for avoiding the same value
delay(50);
}
if (DEBUG)
Serial.println("End generation");
}
/*
* Generate a random value from the analog input
* Store the value in the entropy structure at the position specified in argument
*/
static void generateEntropy(int position){
int sensorValue = 0;
while( sensorValue == 0){
sensorValue = analogRead(SENSOR_PIN);
if (sensorValue != 0){
if (DEBUG)
Serial.println("Value: " + String(sensorValue));
if(sensorValue <= 10)
sensorValue = sensorValue << 5;
else if(sensorValue > 10 && sensorValue <= 100)
sensorValue = sensorValue << 4;
s_entropy.buf[position] = sensorValue;
Serial.println("Position: " + String(position));
}
}
}
/*
* For avoiding to reused the seed, we must generate a new one
*/
static unsigned long generateSeed(){
unsigned long seed;
int sensorValue = 0;
if (DEBUG)
Serial.println("Generate seed");
while (sensorValue == 0){
sensorValue = analogRead(SENSOR_PIN);
seed = sensorValue;
if (DEBUG)
Serial.println("Seed: " + String(seed));
}
return seed;
}
/*
* Generate a random data from the entropy pool
*/
unsigned long prng(){
unsigned long p = 0;
unsigned long pos = generateSeed();
pos += ( (pos << 4));
pos ^= ( (pos >> 11));
pos |= (pos << (pos % 15));
pos = pos % 201;
if (pos > BUFSIZE)
pos = pos / 2;
p = s_entropy.buf[pos];
// Replace the old value
generateEntropy(pos);
return p;
}