Giter VIP home page Giter VIP logo

Comments (1)

stone14z avatar stone14z commented on August 10, 2024

The pw_random_number function can be re-written as follows to remove the modulo bias

/*

  • Generate a random number n, where 0 <= n < max_num, using

  • /dev/urandom if possible.

  • max_num is never greater than 127 for this application
    */
    int pw_random_number(max_num)
    int max_num;
    {
    unsigned char rand_num = 0xff;
    unsigned char mask = 0x7f;
    int i, fd = get_random_fd();
    int lose_counter = 0x1f;
    char *cp = (char *) &rand_num;

    if (max_num <= 0x3f) mask = 0x3f;
    if (max_num <= 0x1f) mask = 0x1f;

    if (fd >= 0) {
    while (rand_num >= (unsigned int)max_num) { // while loop removes modulo bias
    i = read(fd, cp, 1);
    rand_num &= mask;
    if ((i < 0) &&
    ((errno == EINTR) || (errno == EAGAIN)))
    continue;
    if (i <= 0) {
    if (!lose_counter--) break;
    continue;
    }
    }
    close(fd);
    return (rand_num);
    }

    /* We weren't able to use /dev/random, fail hard */

    fprintf(stderr, "No entropy available!\n");
    exit(1);
    }

from pwgen.

Related Issues (9)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.