我正在创建一个 C 程序来生成密码。
C 中的rand()
即使使用 srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL) 也会不断生成一些相同的字符串集))
发现于 here但比使用 srand(time(NULL)) 更好
我找到了这个answer ,我终于知道如何将 libsodium 链接到我的项目了。
之后,我意识到我只能设置 randombytes_uniform()
的上限,下限始终为 0
。
并使用randombytes_random()
给我所有不能在密码中使用的字符。
有人知道如何使用钠或任何安全的方式生成字符来生成字符空间(32)到字符〜(126)吗?
原代码如下:
#include <stdio.h>
#include <stdlib.h>
#include "sodium.h"
#pragma warning (disable:4996)
void main(int argc, char **argv){
/* Length of the password */
int length, num, temp, number;
num = 10;
length = 10;
number = num;
clear_screen();
/* Seed number for rand() */
srand((unsigned int)**generate_standard_password + (unsigned int)&argc + (unsigned int)time(0));
while (num--)
{
temp = length;
printf("\n\t%2d. ", (number - num));
while (temp--) {
putchar(rand() % 56 + 65);
srand(rand());
}
temp = length;
}
printf("\n\n\t");
system_pause();
}
最佳答案
共有 126 - 32 + 1 = 95 个字符供您选择。因此,将 rand
的结果除以 95,然后加上 32。这将给您一个您想要的范围内的数字。
您不断获得相同字符集的原因是因为您在每次调用后都重新播种。您应该在启动时只播种一次,
while (temp--) {
putchar((rand() % 95) + 32);
}
关于c - 无论如何,是否可以使用odium.h 生成字符空间(32) 到~(126) ?或者其他生成安全字符串的方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44222866/