这是在 C 或 C++ 中生成随机字节数组的好方法吗?

Is this a good approach to random byte array genaration in C or C++?

本文关键字:数组 字节数 字节 方法 随机 C++      更新时间:2023-10-16

我知道这里已经讨论过这种问题:如何在 C 中生成随机数?

但我想分享我实现它的方式,只是为了了解人们可能会怎么想它。

#include <stdlib.h>
#include <string.h>
#include <sys/time.h>
#include <time.h>
long int getNanoSecs(){
    struct timespec unixtimespec;
    clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
    return unixtimespec.tv_nsec;
}

...

unsigned char personal_final_token[PERSONAL_FINAL_TOKEN_SIZE_SIZE];
                unsigned char pwd_ptr_ctr;
                srandom(getNanoSecs()*(getNanoSecs()&0xFF));
                for(pwd_ptr_ctr=0;pwd_ptr_ctr<PERSONAL_FINAL_TOKEN_SIZE_SIZE;pwd_ptr_ctr++){
                    memset(personal_final_token+pwd_ptr_ctr,(random()^getNanoSecs())&0xFF,1);
                }

只需定义PERSONAL_FINAL_TOKEN_SIZE_SIZE,您就可以生成所需大小的随机令牌。

小心你的时钟源,否则你可能会得到意想不到的结果:

#include <stdio.h>
#include <linux/time.h>
#define SAMPLES 10
long getNanoSecs(){
  struct timespec unixtimespec;
  clock_gettime(CLOCK_REALTIME_COARSE, &unixtimespec);
  return unixtimespec.tv_nsec;
}
int main (int argc, char* argv[]) {
  int i;
  long clocks[SAMPLES];
  for (i = 0; i < SAMPLES; i++)
    clocks[i] = getNanoSecs();
  for (i = 0; i < SAMPLES; i++)
    printf("%lun", getNanoSecs());
  return 0;
}

[tbroberg@www src]$ ./a.out727544983728544969728544969728544969728544969728544969728544969728544969728544969728544969

你绝对是对的,我想补充一点,我修改了CLOCK_REALTIME_COARSE CLOCK_REALTIME

根据Linux人:

"CLOCK_REALTIME测量实际(即挂钟(时间的系统范围时钟。设置此时钟需要适当的权限。 该时钟受到系统时间不连续跳跃(例如,如果系统管理员手动更改时钟(以及 adjtime(3( 和 NTP 执行的增量调整的影响。

CLOCK_REALTIME_COARSE(从 Linux 2.6.32 开始;特定于 Linux(CLOCK_REALTIME的更快但不太精确的版本。 当您需要非常快速但不是细粒度的时间戳时,请使用。

但是谢谢你的YOUR_TIME :)