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:
parent
ad71a16e61
commit
196cabe012
20
rand.c
20
rand.c
@ -37,7 +37,6 @@ int finalize_rand(void)
|
||||
{
|
||||
int err = fclose(f);
|
||||
f = NULL;
|
||||
|
||||
return err;
|
||||
}
|
||||
|
||||
@ -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
4
rand.h
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user