r/C_Programming • • 2d ago

Review Help with seed generation for RNG.

typedef int8_t i8;
typedef int16_t i16;
typedef int32_t i32;
typedef int64_t i64;
typedef uint8_t u8;
typedef uint16_t u16;
typedef uint32_t u32;
typedef uint64_t u64;

typedef float f32;
typedef double f64;

i8 RANDOM_SEED(){
    static i8 seed = 0;
    static i8 init = 0;

    if (init) return seed;

    FILE *pF = fopen("SEED_FILE", "rb");

    if (pF) {
        fread(&seed, sizeof(i8), 1, pF);   
    }
    else {
        i8 created = 0;

        srand((u32)time(NULL));
        seed = (i8)(rand() % 246 - 128);

        do {  
            pF = fopen("SEED_FILE", "wb");
            if(pF){
                fwrite(&seed, sizeof(i8), 1, pF);
                created = 1;
            }
        } while(created != 1);
    }

    fclose(pF);
    pF = NULL;
    init = 1;
    return seed;
}

I'm trying to make a seed generator. How it works: you call the function and it creates a seed file with a raw binary value inside it that cannot be read by a human. The program reads it and produces a seed that will always be the same for one computer but will vary from computer to computer. I will use it to make a random number generator whose output is constant on the same machine but differs across machines. Can you tell me if this is efficient, or am I overdoing, underdoing, or overcomplicating things? And also I want to make it memory efficient.
I am making this to clarify my concept on file reading - writing and RNG.

5 Upvotes

30 comments sorted by

6

u/tstanisl 1d ago

8bit is not especially great amount of entropy to work with. Good quality generators use thousands. For just statistically correct noise generators (which rand() IS NOT) 64 bit is usually enough. I don't see the point of storing to a file. Just dump it to logs and add an option for user to pass it explicitly. Otherwise use date or /dev/random.

1

u/Parking_Impress539 1d ago

aight i will look into it

4

u/No_External_4869 1d ago

It's fine if they're learning. 

3

u/MFFVD 1d ago

while(created != 1)? that seems a bit strange for errorhandling

1

u/Parking_Impress539 1d ago

yeah error is a mess ig rn

1

u/MFFVD 1d ago

you should at least use errno to get the actual error and just print and exit if its not recoverable

5

u/mjmvideos 1d ago

Explain your thinking on “cannot be read by a human”. Any file in a file system can be read by a human.

1

u/Parking_Impress539 1d ago

dramatic effects and "�" this is what I got in the SEED_FILE

5

u/mjmvideos 1d ago

Well you can’t decode a binary file in ASCII, but you can read it with a hex editor.

3

u/Parking_Impress539 1d ago

okay thanks. my bad on that

3

u/No_External_4869 1d ago

That isn't really a secret, just "not nice" characters, seed file is still public. For learning it's fine. 

5

u/mikeblas 1d ago

"Human readable" means unencoded, plain text.

9

u/No_External_4869 1d ago
  1. I dont get that do while. Why error handling like this?
  2. You can avoid init by checking what fread and fopen have to say about your SEED_FILE.
  3. You can probably cast rand() output directly to your i8 which should truncate it automatically. 

2

u/No_External_4869 1d ago

Also, rand's lower bits sometimes have poor entropy, do (rand() >> 8) and use its lower 8.

3

u/sciencekm 1d ago

If you want something that is unique to a computer, you should get all the MAC addresses, the SMBIOS ID and all the drive IDs, then hash all of those.

1

u/marc_b_reynolds 1d ago

Just the network card is probably close enough.

2

u/sciencekm 1d ago

There are NIC manufacturers that recycle their allocated MAC address range. Also, having the same MAC addresses with VMs happen often.

3

u/wwabbbitt 1d ago edited 1d ago

There is no guarantee that this seed you generate will be unique to the computer and remain the same.

Since its seeded by time(NULL), two computers running this at the same time will have the same seed.

If you rerun this program on any computer, the new seed file generated will overwrite the old seed file and your rng output will then be different within the same computer.

EDIT: Just saw that it checks for existing seed file and won't overwrite. In any case, you'd want the seed file to be more resilient to being edited or deleted.

The appropriate way to achieve what you want is to seed your RNG using the unique machine id provided by your OS. On windows you can use the registry item HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Cryptography\MachineGuid on linux you can read it from /etc/machine-id

1

u/Ordinary-Pirate7852 1d ago

    do {  
            pF = fopen("SEED_FILE", "wb");
            if(pF){
                fwrite(&seed, sizeof(i8), 1, pF);
                created = 1;
            }
        } while(created != 1);

why are we looping here

feels kinda wrong calling fopen on an already open file (i might be wrong on this)

1

u/Ordinary-Pirate7852 1d ago

i am wrong on this (im dumb)

1. check if seedfile exists
     if seedfile exists jump to 2, else jump to 3
2. read seed, jump to 4
3. generate random number, write to file, jump to 4
4. cleanup, set initiated

2

u/Ordinary-Pirate7852 1d ago

that said, i feel like having fopen and fclose in the same scope would be better (tho might not be the cleanest way, wcyd im an amateur)

//pass the seed by pointer, use the return value as error state
//0 on success and non zero for failure maybe

i8 RANDOM_SEED(i8 *p_seed){
    static i8 seed = 0;
    static i8 init = 0;
    if (init) {
      *p_seed = seed;
      return 0;
    } 

    //if already initialized func wont exec past here

    FILE *pF = fopen("SEED_FILE", "rb");
    if (pF) { //file opened, proceed to read seed
        fread(&seed, sizeof(i8), 1, pF);   
    }
    else { //file open failure, generate new seed
        i8 created = 0;

        srand((u32)time(NULL));
        seed = (i8)(rand() % 246 - 128);

        pF = fopen("SEED_FILE", "wb");
        if(pF){ //file opened in write mode
          fwrite(&seed, sizeof(i8), 1, pF);
          created = 1;
        } 
        else { //file open in write mode failure
          return 1; //failure
        }
    }
    //if file write failed AND not init'd, func wont exec past here
    
    fclose(pF);
    pF = NULL; //maybe redundant
    init = 1;
    *p_seed = seed; // pass by pointer
    return 0; //success
}

1

u/Ordinary-Pirate7852 1d ago

also any file on the system can be read by a human, i assume you meant human readable i.e ASCII

1

u/Parking_Impress539 1d ago

yeah my bad. Thanks

1

u/Parking_Impress539 1d ago

aight imma try this

1

u/Ordinary-Pirate7852 1d ago

check the other reply

1

u/gremolata 1d ago

What case that do-while loop is meant to address?

1

u/MarekKnapek 1d ago

No point of storing just 1Byte if randomness into a file. Whatever you do, your PRNG will start with one of just 256 possibilities. Too few. I can crack your randomness if I try 256 times. Decide what you want to use: Maximal C portability, or real world. In case of real world, just read the /dev/random file or call the CryptGenRandom/BCryptGenRandom/RtlGenRandom function.

1

u/al2o3cr 1d ago
seed = (i8)(rand() % 246 - 128);

Nitpick: this will only return numbers between -128 and 117. Is that on purpose?

1

u/FedUp233 1d ago

If you’re going to store something on one of the drives in the file system, why not just use the drive’s UUID and hash that? There should never be any duplicates.

Or, I’m not that familiar with the security chip that works with secure boot but if there is an api to use that you could just generate a UUID and store that in the secure storage which would essentially be there for the life of the of the pc even if the cpu were replaced or drives replaced.

1

u/0xMattB 1d ago

Why are you typedef'ing common types?