1
0
mirror of https://github.com/trezor/trezor-firmware.git synced 2024-11-22 07:28:10 +00:00

add warning message to rand.c

This commit is contained in:
Pavol Rusnak 2018-01-21 23:38:32 +01:00
parent bb4c3d0525
commit 2e528be1e9
No known key found for this signature in database
GPG Key ID: 91F3B339B9A02A3D
2 changed files with 19 additions and 23 deletions

39
rand.c
View File

@ -25,32 +25,27 @@
#ifndef RAND_PLATFORM_INDEPENDENT
#pragma message("NOT SUITABLE FOR PRODUCTION USE!")
// The following code is not supposed to be used in a production environment.
// It's included only to make the library testable.
// The message above tries to prevent any accidental use outside of the test environment.
//
// You are supposed to replace the random32() function with your own secure code.
// There is also a possibility to replace the random_buffer() function as it is defined as a weak symbol.
#include <stdio.h>
#ifdef _WIN32
#include <time.h>
#else
#include <assert.h>
#endif
uint32_t random32(void)
{
#ifdef _WIN32
static int initialized = 0;
if (!initialized) {
srand((unsigned)time(NULL));
initialized = 1;
}
return ((rand() % 0xFF) | ((rand() % 0xFF) << 8) | ((rand() % 0xFF) << 16) | ((rand() % 0xFF) << 24));
#else
static FILE *frand = NULL;
if (!frand) {
frand = fopen("/dev/urandom", "r");
}
uint32_t r;
size_t len_read = fread(&r, 1, sizeof(r), frand);
assert(len_read == sizeof(r));
return r;
#endif
}
#endif /* RAND_PLATFORM_INDEPENDENT */
@ -59,13 +54,6 @@ uint32_t random32(void)
// The following code is platform independent
//
uint32_t random_uniform(uint32_t n)
{
uint32_t x, max = 0xFFFFFFFF - (0xFFFFFFFF % n);
while ((x = random32()) >= max);
return x / (max / n);
}
void __attribute__((weak)) random_buffer(uint8_t *buf, size_t len)
{
uint32_t r = 0;
@ -77,6 +65,13 @@ void __attribute__((weak)) random_buffer(uint8_t *buf, size_t len)
}
}
uint32_t random_uniform(uint32_t n)
{
uint32_t x, max = 0xFFFFFFFF - (0xFFFFFFFF % n);
while ((x = random32()) >= max);
return x / (max / n);
}
void random_permute(char *str, size_t len)
{
for (int i = len - 1; i >= 1; i--) {

3
rand.h
View File

@ -28,8 +28,9 @@
#include <stdlib.h>
uint32_t random32(void);
uint32_t random_uniform(uint32_t n);
void random_buffer(uint8_t *buf, size_t len);
uint32_t random_uniform(uint32_t n);
void random_permute(char *buf, size_t len);
#endif