Calculate the length of a password for a given entropy and chars.
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)
650455
def length_prefix(length, offset):
    
    if length < 56:
        return chr(offset + length)
    else:
        length_string = int_to_big_endian(length)
        return chr(offset + 56 - 1 + len(length_string)) + length_string
630545
def minimum_entropy_match_sequence(password, matches):
    
    bruteforce_cardinality = calc_bruteforce_cardinality(password) # e.g. 26 for lowercase
    up_to_k = [0] * len(password) # minimum entropy up to k.
    # for the optimal sequence of matches up to k, holds the final match (match['j'] == k). null means the sequence ends
    # without a brute-force character.
    backpointers = []
    for k in range(0, len(password)):
        # starting scenario to try and beat: adding a brute-force character to the minimum entropy sequence at k-1.
        up_to_k[k] = get(up_to_k, k-1) + lg(bruteforce_cardinality)
        backpointers.append(None)
        for match in matches:
            if match['j'] != k:
                continue
            i, j = match['i'], match['j']
            # see if best entropy up to i-1 + entropy of this match is less than the current minimum at j.
            up_to = get(up_to_k, i-1)
            candidate_entropy = up_to + calc_entropy(match)
            if candidate_entropy < up_to_k[j]:
                #print "New minimum: using " + str(match)
                #print "Entropy: " + str(candidate_entropy)
                up_to_k[j] = candidate_entropy
                backpointers[j] = match

    # walk backwards and decode the best sequence
    match_sequence = []
    k = len(password) - 1
    while k >= 0:
        match = backpointers[k]
        if match:
            match_sequence.append(match)
            k = match['i'] - 1
        else:
            k -= 1
    match_sequence.reverse()

    # fill in the blanks between pattern matches with bruteforce "matches"
    # that way the match sequence fully covers the password: match1.j == match2.i - 1 for every adjacent match1, match2.
    def make_bruteforce_match(i, j):
        return {
            'pattern': 'bruteforce',
            'i': i,
            'j': j,
            'token': password[i:j+1],
            'entropy': lg(math.pow(bruteforce_cardinality, j - i + 1)),
            'cardinality': bruteforce_cardinality,
        }
    k = 0
    match_sequence_copy = []
    for match in match_sequence:
        i, j = match['i'], match['j']
        if i - k > 0:
            match_sequence_copy.append(make_bruteforce_match(k, i - 1))
        k = j + 1
        match_sequence_copy.append(match)

    if k < len(password):
        match_sequence_copy.append(make_bruteforce_match(k, len(password) - 1))
    match_sequence = match_sequence_copy

    min_entropy = 0 if len(password) == 0 else up_to_k[len(password) - 1] # corner case is for an empty password ''
    crack_time = entropy_to_crack_time(min_entropy)

    # final result object
    return {
        'password': password,
        'entropy': round_to_x_digits(min_entropy, 3),
        'match_sequence': match_sequence,
        'crack_time': round_to_x_digits(crack_time, 3),
        'crack_time_display': display_time(crack_time),
        'score': crack_time_to_score(crack_time),
    }
76874
def generate_password(self) -> list:
        """"""
        characterset = self._get_password_characters()
        if (
                self.passwordlen is None
                or not characterset
        ):
            raise ValueError("Can't generate password: character set is "
                             "empty or passwordlen isn't set")

        password = []
        for _ in range(0, self.passwordlen):
            password.append(randchoice(characterset))

        self.last_result = password
        return password
1068582
public static int getDBLength(String str, int n) {
		if (str == null) {
			return 0;
		}

		char[] chars = str.toCharArray();
		int len = 0;

		for (int i = 0; i < chars.length; i++) {
			if (Character.UnicodeBlock.of(chars[i]) == Character.UnicodeBlock.BASIC_LATIN) {
				len++;
			} else {
				len += n;
			}
		}

		return len;
	}
374988
def _calc_entropy(data, size=None):
        

        if not data:
            return 0
        entropy = 0
        if size is None:
            size = len(data)

        data = bytes(pyvex.ffi.buffer(data, size))
        for x in range(0, 256):
            p_x = float(data.count(x)) / size
            if p_x > 0:
                entropy += - p_x * math.log(p_x, 2)
        return entropy
607988
public static function makeRandomString( $length, $char_set = 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789_' )
    {
        $ret = '';
        $char_set_cnt = strlen($char_set);

        mt_srand();
        for($i = 0; $i < $length; $i++){
            $idx = mt_rand(0, $char_set_cnt - 1);
            $ret .= $char_set[ $idx ];
        }

        return $ret;
    }
865617
def main():
    
    parser = argparse.ArgumentParser(
        description="Generate random password."
    )
    parser.add_argument("-l", "--length",
                        help="the length of the generated "
                             "password (default: 12)",
                        type=int, default=12)
    parser.add_argument("-n", "--number",
                        help="how many passwords to generate (default: 10)",
                        type=int, default=10)
    parser.add_argument("-p", "--punctuation",
                        help="use punctuation characters",
                        action='store_true')
    parser.add_argument("--limit-punctuation",
                        help="specify allowed punctuation characters",
                        action='store', default='')
    alnum_group = parser.add_mutually_exclusive_group()
    alnum_group.add_argument("--no-digits",
                             help="don't use digits",
                             action='store_false', dest='digits')
    alnum_group.add_argument("--no-letters",
                             help="don't use letters",
                             action='store_false', dest='letters')
    case_group = parser.add_mutually_exclusive_group()
    case_group.add_argument("--upper",
                            help="use only upper case letters",
                            action='store_true')
    case_group.add_argument("--lower",
                            help="use only lower case letters",
                            action='store_true')
    args = parser.parse_args()

    if args.length < 1:
        _error("argument -l/--length must be greater than zero")
    if args.number < 1:
        _error("argument -n/--number must be greater than zero")

    if args.lower:
        case = "lower"
    elif args.upper:
        case = "upper"
    else:
        case = "both"

    for _ in range(args.number):
        print(passgen(args.length, punctuation=args.punctuation,
                      limit_punctuation=args.limit_punctuation,
                      digits=args.digits,
                      letters=args.letters, case=case))
417312
def GeneratePassphrase(length=20):
  """"""
  valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  valid_chars += "0123456789 ,-_&$#"
  return "".join(random.choice(valid_chars) for i in range(length))
1210947
final protected function _validateLength() {
        //validate that required indices exist
        if (!isset($this->_userProfile['username'])
            || !isset($this->_userProfile['password'])
            || !isset($this->_userProfile['fullname'])
            || !isset($this->_userProfile['passhist'])
        ) {
            throw new UserCredentialException('The username and password are not set', 1016);
        }

        //determine which entropy to use (base or udf)
        $entropyObj = $this->_udfEntropySetting;
        
        //perform length check
        if (strlen($this->_userProfile['password']) < $entropyObj['min_pass_len']) {
            throw new UserCredentialException('The password does not meet required length. '.$this->_getPasswordLengthDescription(), \USERCREDENTIAL_ACCOUNTPOLICY_WEAKPASSWD);
        }
        
        return true;
    }
1333125
function entropy($str) {
		$len=strlen($str);
		return 4*min($len,1)+($len>1?(2*(min($len,8)-1)):0)+
			($len>8?(1.5*(min($len,20)-8)):0)+($len>20?($len-20):0)+
			6*(bool)(preg_match(
				'/[A-Z].*?[0-9[:punct:]]|[0-9[:punct:]].*?[A-Z]/',$str));
	}
573762
def p_chars(self, p):
        """"""
        if len(p) == 1:
            p[0] = unicode()
        else:
            p[0] = p[1] + p[2]
271867
private long readLong(ByteBuf chars, int length) {
        long result = 0;
        for (int i = chars.readerIndex(); i < chars.readerIndex() + length; i++) {
            int digit = ((int)chars.getByte(i) & 0xF);
            for (int j = 0; j < chars.readerIndex() + length-1-i; j++) {
                digit *= 10;
            }
            result += digit;
        }
        chars.readerIndex(chars.readerIndex() + length);
        return result;
    }
1163561
def _padd_password(self):
        """"""
        password = self.session._auth_password
        if isinstance(password, str):
            password = str.encode(password)
        return password.ljust(16, b'\x00')
408005
def length_range(string, minimum, maximum):
    
    int_range(len(string), minimum, maximum)
    return string
336082
def calculate_content_length(self):
        """"""
        try:
            self._ensure_sequence()
        except RuntimeError:
            return None
        return sum(len(x) for x in self.iter_encoded())
1311069
def entropy(string):
    """"""
    entropy = 0
    for number in range(256):
        result = float(string.encode('utf-8').count(
            chr(number))) / len(string.encode('utf-8'))
        if result != 0:
            entropy = entropy - result * math.log(result, 2)
    return entropy