Search code examples
crandompasswordslibsodium

Is there anyway to generate character space(32) to ~(126) using sodium.h ? Or other way to generate secure string?


I am creating a C program to generate passwords.

rand() in C keep generating some same set of strings even using srand((unsigned int)**main + (unsigned int)&argc + (unsigned int)time(NULL)) found in here but better than using srand(time(NULL))

I found this answer, and I finally know how to link libsodium to my project.

After that, I realise I only can set the upper bound for randombytes_uniform(), the lower bound is always 0.

And using randombytes_random() give me all kind of characters that cannot use in password.

Can anyone know how to generate character space(32) to character ~(126) using sodium or any secure way to generate character?

Here is the original code:

#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();
}

Solution

  • There are 126 - 32 + 1 = 95 characters for you to choose from. So mod the result of rand by 95, then add 32. That will give you a number in the range you want.

    The reason you keep getting the same set of characters is because you're reseeding after every call. You should only seed once at startup,

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