-1

我正在创建一个 C 程序来生成密码。

rand()srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL))在 C 中,即使使用在此处找到的,也会继续生成一些相同的字符串集,但比使用更好srand(time(NULL))

我找到了这个答案,我终于知道如何将 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();
}
4

2 回答 2

2

有 126 - 32 + 1 = 95 个字符供您选择。因此,将结果rand乘以 95,然后加上 32。这将为您提供所需范围内的数字。

您不断获得相同字符集的原因是因为您在每次通话后都在重新播种。你应该只在启动时播种一次,

while (temp--) {
    putchar((rand() % 95) + 32);
}
于 2017-05-28T01:11:34.987 回答
1

不要使用r mod hif hdoesn't divide max(r) + 1,否则输出将偏向较低的值。

rand()函数返回一个介于0和之间的值RAND_MAX,通常为2^31。因此, 的输出rand() % 95更有可能是012比其他值。

这是randombytes_uniform()libsodium 中函数的全部要点:为任意范围提供无偏输出。

randombytes_uniform(95)返回一个介于094(包括)之间的值。32如果这是你想要的,只需添加: 32 + randombytes_uniform(95)

于 2017-05-28T12:45:05.267 回答