1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-12-22 22:38:08 +00:00

import random_uniform and random_permute functions from TREZOR codebase

This commit is contained in:
Pavol Rusnak 2015-03-30 17:45:34 +02:00
parent ad71a16e61
commit 196cabe012
2 changed files with 25 additions and 5 deletions

26
rand.c
View File

@ -35,10 +35,9 @@ void init_rand(void)
int finalize_rand(void)
{
int err = fclose(f);
f = NULL;
return err;
int err = fclose(f);
f = NULL;
return err;
}
uint32_t random32(void)
@ -50,8 +49,27 @@ uint32_t random32(void)
return r;
}
uint32_t random_uniform(uint32_t n)
{
uint32_t x, max = 0xFFFFFFFF - (0xFFFFFFFF % n);
while ((x = random32()) >= max);
return x / (max / n);
}
void random_buffer(uint8_t *buf, size_t len)
{
size_t len_read = fread(buf, 1, len, f);
assert(len_read == len);
}
void random_permute(char *str, size_t len)
{
int i, j;
char t;
for (i = len - 1; i >= 1; i--) {
j = random_uniform(i + 1);
t = str[j];
str[j] = str[i];
str[i] = t;
}
}

4
rand.h
View File

@ -24,12 +24,14 @@
#ifndef __RAND_H__
#define __RAND_H__
#include <stdlib.h>
#include <stdint.h>
#include <stdlib.h>
void init_rand(void);
int finalize_rand(void);
uint32_t random32(void);
uint32_t random_uniform(uint32_t n);
void random_buffer(uint8_t *buf, size_t len);
void random_permute(char *buf, size_t len);
#endif