Search code examples
crandombytebitcoinpuzzle

How to get customized bytes from /dev/urandom?


I am working on a program that finds partial collision in Bitcoin addresses. I have obtained source code for urandom and don't see where to start. So I want to get random bytes from /dev/urandom of length 32 in total (including the masking 0s) because my program expects 256 bit but masked with zeros at the beginning when converted to hex.

The hex output would be like this

000000000000000000000000000000000000000000000000000000000000002d4

Notice the 0s before the actual Hex value( that's what I am calling a mask), in python it is needed by many libraries to get Bitcoin address.

I am struggling with the following code (not from random.c), now I think modifying urandom itself could be more helpful.

   static bool init_rand(void *data, size_t size)
{
    FILE *stream = fopen("/dev/urandom", "r");
    if (stream == NULL)
        return false;
    bool ok = (fread(data, sizeof(uint8_t), size, stream) == size);
    fclose(stream);
    return ok;
}



static bool init_rand(void *data, size_t size)
{
    size_t size0 = size / sizeof(unsigned) + 1;
    assert(size0 * sizeof(unsigned) >= size);
    unsigned data0[size0];
    for (size_t i = 0; i < size0; i++)
    {
        int err = rand_s(data0 + i);
        if (err != 0)
            return false;
    }
    memcpy(data, data0, size);
    return true;
}


static struct seed *make_seed(void)
{
    struct seed *seed = (struct seed *)malloc(sizeof(struct seed));
    assert(seed != NULL);
    seed->counter = 0;
    if (!init_rand(seed, sizeof(struct seed)))
    {
        fprintf(stderr, "error: failed to init random seed\n");
        exit(EXIT_FAILURE);
    }
    if (seed->counter == 0)     // Sanity check...
    {
        fprintf(stderr, "error: random seed initialization failed\n");
        exit(EXIT_FAILURE);
    }
    return seed;
}

For Full code please see Pairgen Here.

Is it possible to modify random.c from Linux kernel drivers to produce bytes already masked with 0s?


Solution

  • memset is what can mask bytes with zeroes. that helped me except i had to do it in rand256(seed) function though

    static uint256_t rand256(struct seed *seed)
    {
        seed->counter++;
        return sha256(seed, sizeof(struct seed));
    }
    
    static uint256_t rand256_and_mask(struct seed *seed)
    {
        //Generate 256-bit random number using rand256 function
        uint256_t r = rand256(seed);
        memset(&r, 0, 24); //mask first  bytes leaving 8 intact
        return r;
    }