2017-05-28 18 views
-1

我正在創建一個C程序來生成密碼。有沒有辦法使用sodium.h生成〜(126)的字符空間(32)?或者其他方式來生成安全的字符串?

rand()用C不斷產生一些相同的一組甚至使用here,但更好的發現srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL))字符串比使用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(); 
} 

回答

1

有126 - 32 + 1 = 95個字符爲您選擇。因此,將rand的結果修改95,然後加上32.這會給你一個你想要的範圍內的數字。

您繼續獲得相同字符集的原因是因爲您在每次通話後重新接種。您應該只在啓動時種子一次

while (temp--) { 
    putchar((rand() % 95) + 32); 
} 
0

不要使用r mod h如果h不分max(r) + 1,否則輸出將朝較低的值有偏差。

rand()函數返回0RAND_MAX之間的值,該值通常爲2^31。因此rand() % 95的輸出比其他值更可能是0,12

這是libsodium中randombytes_uniform()函數的全部:爲任意範圍提供無偏輸出。

randombytes_uniform(95)返回094(含)之間的值。只要加上32,如果這是你想要的:32 + randombytes_uniform(95)