Skip to content

Commit

Permalink
updating crypto/rand to use Flipper Zero specific hardware RNG
Browse files Browse the repository at this point in the history
  • Loading branch information
xtruan committed Mar 1, 2023
1 parent 6619222 commit deb57aa
Showing 1 changed file with 34 additions and 15 deletions.
49 changes: 34 additions & 15 deletions crypto/rand.c
Original file line number Diff line number Diff line change
Expand Up @@ -21,12 +21,19 @@
* OTHER DEALINGS IN THE SOFTWARE.
*/

// NOTE:
// random32() and random_buffer() have been replaced in this implementation
// with Flipper Zero specific code. The original code is commented out below.

#include "rand.h"

// Flipper Zero RNG code:
#include <furi_hal_random.h>

#ifndef RAND_PLATFORM_INDEPENDENT

#pragma message( \
"NOT SUITABLE FOR PRODUCTION USE! Replace random32() function with your own secure code.")
// Original code:
// #pragma message("NOT SUITABLE FOR PRODUCTION USE! Replace random32() function with your own secure code.")

// The following code is not supposed to be used in a production environment.
// It's included only to make the library testable.
Expand All @@ -41,11 +48,22 @@ static uint32_t seed = 0;

void random_reseed(const uint32_t value) { seed = value; }

// Original code:
// uint32_t random32(void) {
// // Linear congruential generator from Numerical Recipes
// // https://en.wikipedia.org/wiki/Linear_congruential_generator
// seed = 1664525 * seed + 1013904223;
// return seed;
// }

// Flipper Zero RNG code:
uint32_t random32(void) {
// Linear congruential generator from Numerical Recipes
// https://en.wikipedia.org/wiki/Linear_congruential_generator
seed = 1664525 * seed + 1013904223;
return seed;
return furi_hal_random_get();
}

// Flipper Zero RNG code:
void random_buffer(uint8_t *buf, size_t len) {
furi_hal_random_fill_buf(buf, len);
}

#endif /* RAND_PLATFORM_INDEPENDENT */
Expand All @@ -54,15 +72,16 @@ uint32_t random32(void) {
// The following code is platform independent
//

void __attribute__((weak)) random_buffer(uint8_t *buf, size_t len) {
uint32_t r = 0;
for (size_t i = 0; i < len; i++) {
if (i % 4 == 0) {
r = random32();
}
buf[i] = (r >> ((i % 4) * 8)) & 0xFF;
}
}
// Original code:
// void __attribute__((weak)) random_buffer(uint8_t *buf, size_t len) {
// uint32_t r = 0;
// for (size_t i = 0; i < len; i++) {
// if (i % 4 == 0) {
// r = random32();
// }
// buf[i] = (r >> ((i % 4) * 8)) & 0xFF;
// }
// }

uint32_t random_uniform(uint32_t n) {
uint32_t x = 0, max = 0xFFFFFFFF - (0xFFFFFFFF % n);
Expand Down

0 comments on commit deb57aa

Please sign in to comment.