Home > Net >  Efficient way to repeatedly generate same random number in C ?
Efficient way to repeatedly generate same random number in C ?

Time:11-22

I am working on a secure LoRa transmission, where I need to generate the same pseudo-random number on the transmitter and the receiver (it would be part of the encryption algorithm) based on an input counter. So this function should give the same output for a given input, just like a hashing algorithm.

As an example here is what I mean, but as you can see the computation gets longer based on the input:

`

unsigned int f(unsigned int input) {
  srand(1234);
  for (unsigned int i = 0; i < input; i  ) {
    rand();
  }
  return rand();
}

`

Is there a more efficient way to do this? I am on an ESP32 microcontroller.

CodePudding user response:

You should not use rand for this purpose as it is implementation-defined which presents a couple of issues for your use-case:

  • It may produce different numbers on different targets
  • It is not guaranteed to be cryptographically secure

What you describe is a cryptographic hash function. There are many libraries available which offer these. Generally there is a trade-off between security and performance, so you will have to select one.

it would be part of the encryption algorithm

If the application must be truly secure, I would recommend using an existing algorithm such as AES rather than trying to write your own, as it appears you are trying to do here. Again, these are available as libraries, some of which are small and suitable for embedded systems such as tiny-AES.

CodePudding user response:

Here a nice question arose today, presenting standard functions for random generation: Get the state (seed) of a distribution of random numbers

  • Related