randombytes.c 609 Bytes
Newer Older
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
#include "randombytes.h"
#include "main.h"
#include "stm32f7xx.h"
#include <stdint.h>


RNG_HandleTypeDef hrng;

void init_rng(void)
{
  hrng.Instance = RNG;
  if (HAL_RNG_Init(&hrng) != HAL_OK) {
    Error_Handler();
  }
}

uint32_t rand32(void) {
  uint32_t myrndnum=0;
  HAL_RNG_GenerateRandomNumber(&hrng, &myrndnum);

  return myrndnum;
}

void randombytes(unsigned char* x, unsigned long long len) {
  while (len >= 4) {
    *(uint32_t*)x = rand32();
    x += 4;
    len -= 4;
  }
  if (len == 0) return;
  uint32_t rnd = rand32();
  while (len) {
    *x = rnd;
    rnd >>= 8;
    x++;
    len--;
  }
}