简体   繁体   English

在 C++ 中重复生成相同随机数的有效方法?

[英]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.我正在研究安全的 LoRa 传输,我需要根据输入计数器在发射器和接收器上生成相同的伪随机数(这将是加密算法的一部分)。 So this function should give the same output for a given input, just like a hashing algorithm.所以对于给定的输入,这个 function 应该给出相同的 output,就像哈希算法一样。

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.我在 ESP32 微控制器上。

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.我本来可以用 CRC function 完成我想做的事情,但根据你的建议,我最终放弃了这种方法,转而使用标准加密算法。

You should not use rand for this purpose as it is implementation-defined which presents a couple of issues for your use-case:您不应将rand用于此目的,因为它是实现定义的,这会为您的用例带来几个问题:

  • 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.你所描述的是一个密码 hash function。有许多图书馆提供这些。 Generally there is a trade-off between security and performance, so you will have to select one.通常需要在安全性和性能之间进行权衡,因此您必须使用 select 之一。

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.如果应用程序必须真正安全,我会建议使用现有的算法,如AES ,而不是尝试编写自己的算法,就像您在此处尝试做的那样。 Again, these are available as libraries, some of which are small and suitable for embedded systems such as tiny-AES .同样,这些可以作为库使用,其中一些很小并且适用于嵌入式系统,例如tiny-AES

Here a nice question arose today, presenting standard functions for random generation: Get the state (seed) of a distribution of random numbers今天出现了一个很好的问题,提出了随机生成的标准函数: 获取随机数分布的 state(种子)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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