-1

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.

edit. Thanks for all the answers. I could have accomplished what I was trying to do with a CRC function, but as per your recommendation I ended up ditching this approach and used a standard encryption algorithm instead.

2 Answers2

3

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.

frankplow
  • 502
  • 1
  • 12
  • 1
    note that at least the ESP32 ARM hardware has AES support which would make things much faster / more efficient, and some API seems to be included in [ESP-IDF hwcrypto](https://github.com/husarnet/esp-idf/blob/master/components/esp32/include/hwcrypto/aes.h). it sounds like OP wants something like AES-CTR, see [here](https://security.stackexchange.com/a/27780/36536) for what to look out for, note that it's easy to destroy security properties by doing things incorrectly! – Sam Mason Nov 22 '22 at 10:59
0

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