Generate a cryptographically secure random string to use for passwords

    Args:
        length (int): Length of password, defaults to 32 characters

    Returns:
        Randomly generated string
436412
def generate_password(length=32):
    
    return ''.join(random.SystemRandom().choice(string.ascii_letters + '!@#$+.,') for _ in range(length))
622864
def random(self, length=None):
        
        if length is None:
            length = self._length

        random_num = int(binascii.b2a_hex(os.urandom(length)), 16)
        return int_to_string(random_num, self._alphabet, padding=length)[:length]
167073
def secure_password(length=20, use_random=True):
    '''
    
    '''
    try:
        length = int(length)
        pw = ''
        while len(pw) < length:
            if HAS_RANDOM and use_random:
                while True:
                    try:
                        char = salt.utils.stringutils.to_str(get_random_bytes(1))
                        break
                    except UnicodeDecodeError:
                        continue
                pw += re.sub(
                    salt.utils.stringutils.to_str(r'\W'),
                    str(),  # future lint: disable=blacklisted-function
                    char
                )
            else:
                pw += random.SystemRandom().choice(string.ascii_letters + string.digits)
        return pw
    except Exception as exc:
        log.exception('Failed to generate secure passsword')
        raise CommandExecutionError(six.text_type(exc))
1176919
function createRandomStr(length) {
  const bag = 'abcdefghijklmnopqrstuvwxyz0123456789';
  let generated = '';
  for (let i = 0; i < length; i++) {
    generated += bag[Math.floor(Math.random() * bag.length)];
  }
  return generated;
}
1275737
function(length) {
    var charset = "abcdef0123456789";
    var i;
    var result = "";
    var isOpera = Object.prototype.toString.call(window.opera) == '[object Opera]';
    if(window.crypto && window.crypto.getRandomValues) {
        values = new Uint32Array(length);
        window.crypto.getRandomValues(values);
        for(i=0; i<length; i++) {
            result += charset[values[i] % charset.length];
        }
        return result;
    } else if(isOpera) {//Opera's Math.random is secure, see http://lists.w3.org/Archives/Public/public-webcrypto/2013Jan/0063.html
        for(i=0; i<length; i++) {
            result += charset[Math.floor(Math.random()*charset.length)];
        }
        return result;
    }
    else throw new Error("Your browser sucks and can't generate secure random numbers");
}
873301
public function generateRandomKey(int $length = 32): string
    {
        if ($length < 1) {
            throw new \RuntimeException('First parameter ($length) must be greater than 0');
        }

        // always use random_bytes() if it is available
        if (\function_exists('random_bytes')) {
            return \random_bytes($length);
        }
        throw new \RuntimeException('Function random_bytes not found');
    }
23301
def _random_seed(size=32)
        if defined? OpenSSL::Random
          return OpenSSL::Random.random_bytes(size)
        else
          chars = ("a".."z").to_a + ("A".."Z").to_a + ("0".."9").to_a
          (1..size).collect{|a| chars[rand(chars.size)] }.join        
        end
      end
630517
public static String generateRandomString(int length) {

        char[] chars = "abcdefghijklmnopqrstuvwxyz1234567890".toCharArray();
        StringBuilder sb = new StringBuilder();
        Random random = new Random();
        for (int i = 0; i < 20; i++) {
            char c = chars[random.nextInt(chars.length)];
            sb.append(c);
        }

        return sb.toString();
    }
966475
def random_str_uuid(string_length):
    """"""
    if not isinstance(string_length, int) or not 1 <= string_length <= 32:
        msg = "string_length must be type int where 1 <= string_length <= 32"
        raise ValueError(msg)
    random = str(uuid.uuid4()).upper().replace('-', '')
    return random[0:string_length]
452843
def random(length: int = 8, chars: str = digits + ascii_lowercase) -> Iterator[str]:
    
    while True:
        yield "".join([choice(chars) for _ in range(length)])
673287
def rand_ascii_str(length):
    
    letters = [random.choice(ascii_letters_and_digits) for _ in range(length)]
    return ''.join(letters)
873246
def password_entropy(length: int, chars: str) -> float:
    """"""
    if not isinstance(length, int):
        raise TypeError('length can only be int')
    if length < 0:
        raise ValueError('length should be greater than 0')
    if not isinstance(chars, str):
        raise TypeError('chars can only be string')
    if not chars:
        raise ValueError("chars can't be null")

    if length == 0:
        return 0.0

    entropy_c = entropy_bits(list(chars))
    return float(length * entropy_c)
331271
def random(length, chars=None):
    
    if chars is None:
        chars = string.ascii_letters + string.digits
    else:
        ensure_string(chars)
        if not chars:
            raise ValueError("character set must not be empty")

    if is_pair(length):
        length = randint(*length)
    elif isinstance(length, Integral):
        if not length > 0:
            raise ValueError(
                "random string length must be positive (got %r)" % (length,))
    else:
        raise TypeError("random string length must be an integer; "
                        "got '%s'" % type(length).__name__)

    return join(chars.__class__(), (choice(chars) for _ in xrange(length)))
1138245
def generate_random_string(cls, length):
        
        # avoid things that could be mistaken ex: 'I' and '1'
        letters = "23456789ABCDEFGHJKLMNPQRSTUVWXYZ"
        return "".join([random.choice(letters) for _ in range(length)])
554973
def get_random_hex(length):
    
    if length <= 0:
        return ''
    return hexify(random.randint(pow(2, length*2), pow(2, length*4)))[0:length]
6330
def password_length_needed(entropybits: Union[int, float], chars: str) -> int:
    """"""
    if not isinstance(entropybits, (int, float)):
        raise TypeError('entropybits can only be int or float')
    if entropybits < 0:
        raise ValueError('entropybits should be greater than 0')
    if not isinstance(chars, str):
        raise TypeError('chars can only be string')
    if not chars:
        raise ValueError("chars can't be null")

    # entropy_bits(list(characters)) = 6.554588
    entropy_c = entropy_bits(list(chars))
    return ceil(entropybits / entropy_c)
129277
public String generateRandomToken(int length) {
        final char[] token = new char[length];

        for (int i = 0; i < length; i++) {
            final int tokenIndex = random.nextInt(this.tokenChars.length);
            token[i] = tokenChars[tokenIndex];
        }

        return new String(token);
    }