简体   繁体   中英

Efficient way to repeatedly generate same random number in C++?

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.

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 .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM