Generate a random password, similar to
	http://www.pctools.com/guides/password
765446
def password(rest):
	
	charsets = [
		string.ascii_lowercase,
		string.ascii_uppercase,
		string.digits,
		string.punctuation,
	]
	passwd = []

	try:
		length = rest.strip() or 12
		length = int(length)
	except ValueError:
		return 'need an integer password length!'

	for i in range(length):
		passwd.append(random.choice(''.join(charsets)))

	if length >= len(charsets):
		# Ensure we have at least one character from each charset
		replacement_indices = random.sample(range(length), len(charsets))
		for i, charset in zip(replacement_indices, charsets):
			passwd[i] = random.choice(charset)

	return ''.join(passwd)
1243587
def _random_key(self):
        
        hashstr = '%s%s' % (random.random(), self.time_module.time())
        return hashlib.md5(hashstr).hexdigest()
469605
public function getRandomPassword()
	{
		//Random rand = new Random();
		//int type, number;
		$password = "";
		for($i=0; $i<7; $i++)
		{
			$type = rand(0,21) % 3;
			$number = rand(0,25);
			if ($type == 1)
			{
				$password = $password . chr(48 + ($number%10));
			}
			else
			{
				if ($type == 2)
				{
					$password = $password  . chr(65 + $number);

				}
				else
				{
					$password  = $password . chr(97 + $number);

				}
			}
		}
		return $password;
	}
176070
def generate_keypair(crypto, seed, password=None):
    
    if crypto in ['eth', 'etc']:
        raise CurrencyNotSupported("Ethereums not yet supported")

    pub_byte, priv_byte = get_magic_bytes(crypto)
    priv = sha256(seed)
    pub = privtopub(priv)

    priv_wif = encode_privkey(priv, 'wif_compressed', vbyte=priv_byte)
    if password:
        # pycrypto etc. must be installed or this will raise ImportError, hence inline import.
        from .bip38 import Bip38EncryptedPrivateKey
        priv_wif = str(Bip38EncryptedPrivateKey.encrypt(crypto, priv_wif, password))

    compressed_pub = encode_pubkey(pub, 'hex_compressed')
    ret = {
        'public': {
            'hex_uncompressed': pub,
            'hex': compressed_pub,
            'address': pubtoaddr(compressed_pub, pub_byte)
        },
        'private': {
            'wif': priv_wif
        }
    }
    if not password:
        # only these are valid when no bip38 password is supplied
        ret['private']['hex'] = encode_privkey(priv, 'hex_compressed', vbyte=priv_byte)
        ret['private']['hex_uncompressed'] = encode_privkey(priv, 'hex', vbyte=priv_byte)
        ret['private']['wif_uncompressed'] = encode_privkey(priv, 'wif', vbyte=priv_byte)

    return ret
892889
def generate_password(self):
        

        if self.password_failed:
            self.logger.warning("Skipping resetting password since last attempt failed")
            return

        # Set a random password so it's available via cci org info
        command = sarge.shell_format(
            "sfdx force:user:password:generate -u {0}", self.username
        )
        self.logger.info(
            "Generating scratch org user password with command {}".format(command)
        )
        p = sarge.Command(
            command,
            stdout=sarge.Capture(buffer_size=-1),
            stderr=sarge.Capture(buffer_size=-1),
            shell=True,
        )
        p.run()

        stderr = io.TextIOWrapper(p.stderr).readlines()
        stdout = io.TextIOWrapper(p.stdout).readlines()

        if p.returncode:
            self.config["password_failed"] = True
            # Don't throw an exception because of failure creating the
            # password, just notify in a log message
            self.logger.warning(
                "Failed to set password: \n{}\n{}".format(
                    "\n".join(stdout), "\n".join(stderr)
                )
            )
930196
def pw(min_word_length=3, max_word_length=8, max_int_value=1000, number_of_elements=4, no_special_characters=False):
    

    # Set the position of the integer
    int_position = set_int_position(number_of_elements)

    # Load dictionary
    dictionary = load_dictionary()

    password = ''
    for i in range(number_of_elements):
        # Add word or integer
        if i == int_position:
            password += str(get_random_int(max_int_value))
        else:
            password += get_random_word(dictionary,
                                        min_word_length,
                                        max_word_length).title()

        # Add separator
        if i != number_of_elements - 1:
            password += get_random_separator(no_special_characters)

    return password
1141384
def _random(self, key):
        """"""

        if hasattr(key, "encode"):
            key = key.encode('ascii')

        value = (zlib.crc32(key, self.seed) & MAX_VALUE)

        return value * INV_MAX_VALUE
180662
protected function generateRandomPassword()
    {
        $alphabet = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890+*=-_/()!?[]{}';
        $password = array();
        $alphabetLength = strlen($alphabet) - 1;
        
        for ($i = 0; $i < 10; $i++) {
            $charIndex = mt_rand(0, $alphabetLength);
            $password[] = $alphabet[$charIndex];
        }
        
        $password = implode('', $password);
        
        if (!preg_match('/\d/', $password)) {
            $password = mt_rand(0, 9) . $password . mt_rand(0, 9);
        }
        
        return $password;
    }
447686
def generate_random_token(length=32):
    
    chars = (string.ascii_lowercase + string.ascii_uppercase + string.digits)
    return ''.join(random.choice(chars) for _ in range(length))
1250953
def generate_key(key_length=64):
    
    if hasattr(random, 'SystemRandom'):
        logging.info('Generating a secure random key using SystemRandom.')
        choice = random.SystemRandom().choice
    else:
        msg = "WARNING: SystemRandom not present. Generating a random "\
              "key using random.choice (NOT CRYPTOGRAPHICALLY SECURE)."
        logging.warning(msg)
        choice = random.choice
    return ''.join(map(lambda x: choice(string.digits + string.ascii_letters),
                   range(key_length)))
235236
def generate_secret(length=30):
    
    rand = random.SystemRandom()
    ascii_characters = string.ascii_letters + string.digits

    return ''.join(rand.choice(ascii_characters) for _ in range(length))
1226170
public static function random_password($length = 8)
	{
		$genpass = '';
		$salt = "abchefghjkmnpqrstuvwxyz0123456789";

		srand((double)microtime()*1000000);

		$i = 0;

		while ($i < $length)
		{
			$num = rand() % 33;
			$tmp = substr($salt, $num, 1);
			$genpass = $genpass . $tmp;
			$i++;
		}

		return $genpass;
	}
439873
function generateKey() {
	let result = '';
	for(let i=0; i<16; i++) {
		let idx = Math.floor(Math.random() * CHARS.length);
		result += CHARS[idx];
	}
	return result;
}
319800
def random_id(length):
    """"""

    def char():
        """Generate single random char"""

        return random.choice(string.ascii_letters + string.digits)

    return "".join(char() for _ in range(length))
210166
def password_prompt(ctx, param, value):
    """"""
    if ctx.resilient_parsing:
        return

    if not value:
        if 'password_stdin' in ctx.params:
            with click.open_file('-') as fp:
                value = fp.read().strip('\n')
        else:
            value = click.prompt('Password', hide_input=True)

    click.echo(value)
    return value
727541
def _create_login_secret(challenge, password):
        """"""
        to_hash = (challenge + '-' + password).encode('UTF-16LE')
        hashed = hashlib.md5(to_hash).hexdigest()
        return '{0}-{1}'.format(challenge, hashed)
1149058
def main(argv: list) -> int:
    """"""
    passphrase = Passphrase()

    # Set defaults
    passphrase.entropy_bits_req = ENTROPY_BITS_MIN
    passwordlen_default = passphrase.password_length_needed()
    amount_n_default = 0
    passphrase.amount_n = amount_n_default
    # To avoid loading the wordlist unnecessarily, I'm hardcoding this value
    # It's ok, it's only used to show help information
    amount_w_default = 6

    parser = ArgumentParser(
        formatter_class=RawDescriptionHelpFormatter,
        description='{version_string}\n\n'
        'Generates a cryptographically secure passphrase, based on '
        'a wordlist, or a\npassword, and prints it to standard output.\n'
        'By default, it uses an embedded EFF Large Wordlist for passphrases.\n'
        'Passphrases with less than {wordsamountmin} words are considered '
        'insecure. A safe bet is \nbetween {wordsamountmin} and 7 words, '
        'plus at least a number.\n'
        'For passwords, use at least {passwdmin} characters, but prefer '
        '{passwdpref} or more, using the\ncomplete characters set.\n\n'
        'Instead of words and numbers, a password (random string of '
        'printable\ncharacters from Python String standard) can be generated '
        'by\n-p | --password, specifying the length. It uses uppercase, '
        'lowercase, digits\nand punctuation characters unless otherwise '
        'specified.\n'
        'Also, a UUID v4 string can be generated by --uuid4 or a coin can be '
        'thrown\nwith --coin.\n'
        'A custom wordlist can be specified by -i | --input, the format must '
        'be: \nsingle column, one word per line. If -d | --diceware is used, '
        'the input\nfile is treated as a diceware wordlist (two columns).'
        '\nOptionally, -o | --output can be used to specify an output file '
        '(existing \nfile is overwritten).\n'
        'The number of words is {wordsamountmin} by default, but it '
        'can be changed by -w | --words.\n'
        'The number of numbers is {numsamountmin} by default, but it can be '
        'changed by\n-n | --numbers. The generated numbers are between '
        '{minnum} and {maxnum}.\n'
        'The default separator is a blank space, but any character or '
        'character\nsequence can be specified by -s | --separator.\n'
        '\nExample output:\n'
        '\tDefault parameters:\tchalice sheath postcard modular cider size\n'
        '\tWords=3, Numbers=2:\tdepraved widow office 184022 320264\n'
        '\tPassword, 20 chars:\tsF#s@B+iR#ZIL-yUWKPR'.format(
            version_string=__version_string__,
            minnum=passphrase.randnum_min,
            maxnum=passphrase.randnum_max,
            wordsamountmin=amount_w_default,
            numsamountmin=amount_n_default,
            passwdmin=passwordlen_default,
            passwdpref=passwordlen_default + 4
        )
    )

    parser.add_argument(
        '--version',
        action='store_true',
        help='print program version and licensing information and exit'
    )
    parser.add_argument(
        '--insecure',
        action='store_true',
        default=False,
        help="force password/passphrase generation even if the system's "
             "entropy is too low"
    )
    parser.add_argument(
        '--no-newline',
        action='store_true',
        default=False,
        help="don't print newline at the end of the passphrase/password"
    )
    parser.add_argument(
        '-m',
        '--mute',
        action='store_true',
        default=False,
        help="muted mode: it won't print output, only informational, warning "
             "or error messages (usefull with -o | --output)"
    )
    parser.add_argument(
        '-v',
        '--verbose',
        action='store_true',
        default=False,
        help='print additional information (can coexist with -m | --mute)'
    )
    parser.add_argument(
        '-e',
        '--entropybits',
        type=_bigger_than_zero,
        default=ENTROPY_BITS_MIN,
        help='specify the number of bits to use for entropy calculations '
             '(defaults to {})'.format(ENTROPY_BITS_MIN)
    )
    parser.add_argument(
        '--uuid4',
        action='store_true',
        default=False,
        help='generate an UUID v4 string'
    )
    parser.add_argument(
        '--coin',
        action='store_true',
        default=False,
        help='generate a random coin throw: heads or tails'
    )
    parser.add_argument(
        '-p',
        '--password',
        type=_bigger_than_zero,
        const=-1,
        nargs='?',
        help='generate a password of the specified length from all printable '
             'or selected characters'
    )
    parser.add_argument(
        '--use-uppercase',
        type=_bigger_than_zero,
        const=0,
        nargs='?',
        help='use uppercase characters for password generation or give the '
             'amount of uppercase characters in the passphrase: zero or no '
             'input for all uppercase or any number of uppercase '
             'characters wanted (the rest are lowercase)'
    )
    parser.add_argument(
        '--use-lowercase',
        type=_bigger_than_zero,
        const=0,
        nargs='?',
        help='use lowercase characters for password generation or give the '
             'amount of lowercase characters in the passphrase: zero or no '
             'input for all lowercase (default) or any number of lowercase '
             'characters wanted (the rest are uppercase)'
    )
    parser.add_argument(
        '--use-digits',
        action='store_true',
        default=False,
        help='use digits for password generation'
    )
    parser.add_argument(
        '--use-alphanumeric',
        action='store_true',
        default=False,
        help='use lowercase and uppercase characters, and digits for password '
             'generation (equivalent to --use-lowercase --use-uppercase '
             '--use-digits)'
    )
    parser.add_argument(
        '--use-punctuation',
        action='store_true',
        default=False,
        help='use punctuation characters for password generation'
    )
    parser.add_argument(
        '-w',
        '--words',
        type=_bigger_than_zero,
        help='specify the amount of words (0 or more)'
    )
    parser.add_argument(
        '-n',
        '--numbers',
        type=_bigger_than_zero,
        default=amount_n_default,
        help='specify the amount of numbers (0 or more)'
    )
    parser.add_argument(
        '-s',
        '--separator',
        type=str,
        default=' ',
        help='specify a separator character (space by default)'
    )
    parser.add_argument(
        '-o',
        '--output',
        type=str,
        help='specify an output file (existing file is overwritten)'
    )
    parser.add_argument(
        '-i',
        '--input',
        type=str,
        help='specify an input file (it must have the following format: '
             'single column, one word per line)'
    )
    parser.add_argument(
        '-d',
        '--diceware',
        action='store_true',
        default=False,
        help='specify input file as a diceware list (format: two colums)'
    )

    args = parser.parse_args(argv)

    inputfile = args.input
    outputfile = args.output
    separator = args.separator
    is_diceware = args.diceware
    passwordlen = args.password
    amount_w = args.words
    amount_n = args.numbers
    show_version = args.version
    mute = args.mute
    verbose = args.verbose
    no_newline = args.no_newline
    gen_uuid4 = args.uuid4
    gen_coin = args.coin
    p_uppercase = args.use_uppercase
    p_lowercase = args.use_lowercase
    p_digits = args.use_digits
    p_punctuation = args.use_punctuation
    p_alphanumeric = args.use_alphanumeric
    entropy_bits = args.entropybits
    gen_insecure = args.insecure

    if show_version:
        print(__version_string__)
        return 0

    if verbose:
        Aux.print_stderr(__version_string__)

    # Check system entropy
    system_entropy = Aux.system_entropy()
    if system_entropy < SYSTEM_ENTROPY_BITS_MIN:
        Aux.print_stderr(
            'Warning: the system has too few entropy: {} bits; randomness '
            'quality could be poor'.format(system_entropy)
        )
        if not gen_insecure:
            Aux.print_stderr(
                'Error: system entropy too low: {system_entropy} '
                '< {system_entropy_min}'.format(
                    system_entropy=system_entropy,
                    system_entropy_min=SYSTEM_ENTROPY_BITS_MIN
                )
            )
            return 1

    if verbose:
        Aux.print_stderr(
            'Using {} bits of entropy for calculations (if any). The minimum '
            'recommended is {}'.format(entropy_bits, ENTROPY_BITS_MIN)
        )

    # Check selected entropy
    check_chosen_entropy = False if gen_uuid4 or gen_coin else not (
        amount_n and amount_w and passwordlen is None
    )
    if check_chosen_entropy and entropy_bits < ENTROPY_BITS_MIN:
        Aux.print_stderr(
            'Warning: insecure number of bits for entropy calculations '
            'chosen! Should be bigger than {}'.format(ENTROPY_BITS_MIN)
        )
    passphrase.entropy_bits_req = entropy_bits

    # Generate whatever is requested
    if gen_uuid4:
        # Generate uuid4
        if verbose:
            Aux.print_stderr('Generating UUID v4')
        gen_what = 'UUID v4'
        gen_ent = 120

        passphrase.generate_uuid4()
        passphrase.separator = '-'
    elif gen_coin:
        # Generate a coin throw
        if verbose:
            Aux.print_stderr('Throwing a coin')
        gen_what = 'coin'
        gen_ent = 1

        passphrase = 'Heads' if randbool() else 'Tails'
    elif passwordlen is not None:
        # Generate a password
        gen_what = 'password'

        p_uppercase = True if p_uppercase is not None else False
        p_lowercase = True if p_lowercase is not None else False
        if (
                p_uppercase
                or p_lowercase
                or p_digits
                or p_punctuation
                or p_alphanumeric
        ):
            passphrase.password_use_uppercase = (p_uppercase or p_alphanumeric)
            passphrase.password_use_lowercase = (p_lowercase or p_alphanumeric)
            passphrase.password_use_digits = (p_digits or p_alphanumeric)
            passphrase.password_use_punctuation = p_punctuation

        min_len = passphrase.password_length_needed()
        if passwordlen < 1:
            passwordlen = min_len
        elif passwordlen < min_len:
            Aux.print_stderr(
                'Warning: insecure password length chosen! Should be bigger '
                'than or equal to {}'.format(min_len)
            )

        passphrase.passwordlen = passwordlen
        gen_ent = passphrase.generated_password_entropy()

        if verbose:
            verbose_string = (
                'Generating password of {} characters long '
                'using '.format(passwordlen)
            )
            verbose_string += (
                'uppercase characters, ' if (
                    passphrase.password_use_uppercase or p_alphanumeric
                ) else ''
            )
            verbose_string += (
                'lowercase characters, ' if (
                    passphrase.password_use_lowercase or p_alphanumeric
                ) else ''
            )
            verbose_string += (
                'digits, ' if (
                    passphrase.password_use_digits or p_alphanumeric
                ) else ''
            )
            verbose_string += (
                'punctuation characters, ' if (
                    passphrase.password_use_punctuation
                ) else ''
            )
            Aux.print_stderr(
                verbose_string[:-2] if (
                    verbose_string[-2:] == ', '
                ) else verbose_string
            )

        passphrase.generate_password()
        passphrase.separator = ''
    else:
        # Generate a passphrase
        gen_what = 'passphrase'

        # Read wordlist if indicated
        if inputfile is None:
            passphrase.load_internal_wordlist()
        else:
            try:
                passphrase.import_words_from_file(inputfile, is_diceware)
            except IOError:
                Aux.print_stderr(
                    "Error: input file {} is empty or it can't be opened or "
                    "read".format(inputfile)
                )
                return 1

        passphrase.amount_n = amount_n
        amount_w_good = passphrase.words_amount_needed()
        if amount_w is None:
            amount_w = amount_w_good
        elif amount_w < amount_w_good:
            Aux.print_stderr(
                'Warning: insecure amount of words chosen! Should be '
                'bigger than or equal to {}'.format(amount_w_good)
            )

        passphrase.amount_w = amount_w
        gen_ent = passphrase.generated_passphrase_entropy()

        if verbose:
            Aux.print_stderr(
                'Generating a passphrase of {} words and {} '
                'numbers using {}'.format(
                    amount_w,
                    amount_n,
                    'internal wordlist' if inputfile is None else (
                        'external wordlist: ' + inputfile + (
                            ' (diceware-like)' if is_diceware else ''
                        )
                    )
                )
            )

        case = (-1 * p_lowercase) if p_lowercase else p_uppercase
        passphrase.generate(case)
        passphrase.separator = separator

    if verbose:
        Aux.print_stderr(
            'The entropy of this {what} is {ent:.2f} bits'.format(
                what=gen_what,
                ent=gen_ent
            )
        )

    if not gen_coin and gen_ent < ENTROPY_BITS_MIN:
        Aux.print_stderr('Warning: the {} is too short!'.format(gen_what))

    if not mute:
        if no_newline:
            print(passphrase, end='')
        else:
            print(passphrase)

    if outputfile is not None:
        # ensure path to file exists or create
        dir_ = os_path_dirname(outputfile)
        if dir_:
            try:
                os_makedirs(dir_, exist_ok=True)
            except PermissionError:
                Aux.print_stderr(
                    'Error: permission denied to create directory {}'.format(
                        dir_,
                    )
                )
                return 1
        try:
            with open(outputfile, mode='wt', encoding='utf-8') as outfile:
                linefeed = '' if no_newline else '\n'
                outfile.write(str(passphrase) + linefeed)

        except IOError:
            Aux.print_stderr(
                "Error: file {} can't be opened or written".format(
                    outputfile,
                )
            )
            return 1

    return 0