无论如何使用 sodium.h 生成字符 space(32) 到 ~(126) ?或其他生成安全字符串的方法?
Is there anyway to generate character space(32) to ~(126) using sodium.h ? Or other way to generate secure string?
我正在创建一个 C 程序来生成密码。
即使使用 here 中的 srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL))
,C 中的 rand()
也会继续生成一些相同的字符串集,但比使用 srand(time(NULL))
更好
我找到了这个 answer,我终于知道如何 link libsodium 到我的项目中了。
之后,我意识到我只能设置randombytes_uniform()
的上限,下限总是0
。
并使用 randombytes_random()
给我所有不能在密码中使用的字符。
有谁知道如何使用钠或任何安全的方式生成字符 space(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 个字符供您选择。所以 mod rand
的结果乘以 95,然后加上 32。这会给你一个你想要的范围内的数字。
您一直收到相同字符集的原因是您在每次调用后都重新播种。您应该只在启动时播种 一次,
while (temp--) {
putchar((rand() % 95) + 32);
}
如果h
不除max(r) + 1
,请不要使用r mod h
,否则输出将偏向于较低的值。
rand()
函数 returns 介于 0
和 RAND_MAX
之间的值,通常为 2^31
。所以 rand() % 95
的输出比其他值更有可能是 0
、1
或 2
。
这是 libsodium 中 randombytes_uniform()
函数的全部要点:为任意范围提供无偏差输出。
randombytes_uniform(95)
returns 介于 0
和 94
(含)之间的值。如果这是您想要的,只需添加 32
:32 + randombytes_uniform(95)
.
我正在创建一个 C 程序来生成密码。
即使使用 here 中的srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL))
,C 中的 rand()
也会继续生成一些相同的字符串集,但比使用 srand(time(NULL))
我找到了这个 answer,我终于知道如何 link libsodium 到我的项目中了。
之后,我意识到我只能设置randombytes_uniform()
的上限,下限总是0
。
并使用 randombytes_random()
给我所有不能在密码中使用的字符。
有谁知道如何使用钠或任何安全的方式生成字符 space(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 个字符供您选择。所以 mod rand
的结果乘以 95,然后加上 32。这会给你一个你想要的范围内的数字。
您一直收到相同字符集的原因是您在每次调用后都重新播种。您应该只在启动时播种 一次,
while (temp--) {
putchar((rand() % 95) + 32);
}
如果h
不除max(r) + 1
,请不要使用r mod h
,否则输出将偏向于较低的值。
rand()
函数 returns 介于 0
和 RAND_MAX
之间的值,通常为 2^31
。所以 rand() % 95
的输出比其他值更有可能是 0
、1
或 2
。
这是 libsodium 中 randombytes_uniform()
函数的全部要点:为任意范围提供无偏差输出。
randombytes_uniform(95)
returns 介于 0
和 94
(含)之间的值。如果这是您想要的,只需添加 32
:32 + randombytes_uniform(95)
.