Calculate words needed for a passphrase based on entropy.
972085
def words_amount_needed(entropybits: Union[int, float],
                        entropy_w: Union[int, float],
                        entropy_n: Union[int, float],
                        amount_n: int) -> int:
    """"""
    # Thanks to @julianor for this tip to calculate default amount of
    # entropy: minbitlen/log2(len(wordlist)).
    # I set the minimum entropy bits and calculate the amount of words
    # needed, cosidering the entropy of the wordlist.
    # Then: entropy_w * amount_w + entropy_n * amount_n >= ENTROPY_BITS_MIN

    if not isinstance(entropybits, (int, float)):
        raise TypeError('entropybits can only be int or float')
    if not isinstance(entropy_w, (int, float)):
        raise TypeError('entropy_w can only be int or float')
    if not isinstance(entropy_n, (int, float)):
        raise TypeError('entropy_n can only be int or float')
    if not isinstance(amount_n, int):
        raise TypeError('amount_n can only be int')
    if entropybits < 0:
        raise ValueError('entropybits should be greater than 0')
    if entropy_w <= 0:
        raise ValueError('entropy_w should be greater than 0')
    if entropy_n < 0:
        raise ValueError('entropy_n should be greater than 0')
    if amount_n < 0:
        raise ValueError('amount_n should be greater than 0')

    amount_w = (entropybits - entropy_n * amount_n) / entropy_w

    if amount_w > -1.0:
        return ceil(fabs(amount_w))

    return 0
905755
def GetDWORD(self, buff, idx=0):
        '''
        '''
        result = buff[idx] + (buff[idx+1] << 8) + (buff[idx+2] << 16) + \
            (buff[idx+3] << 24)

        if result == 0xFFFFFFFF:
            result = 0

        return result
977561
def entropy_bits(
        lst: Union[
            List[Union[int, str, float, complex]],
            Tuple[Union[int, str, float, complex]]
        ]
) -> float:
    """"""
    # Based on https://stackoverflow.com/a/45091961
    if not isinstance(lst, (list, tuple)):
        raise TypeError('lst must be a list or a tuple')

    for num in lst:
        if not isinstance(num, (int, str, float, complex)):
            raise TypeError('lst can only be comprised of int, str, float, '
                            'complex')

    n_lst = len(lst)

    if n_lst <= 1:
        return 0.0

    # Some NumPy replacements
    counts = [lst.count(x) for x in lst]
    probs = [c / n_lst for c in counts]

    # Compute entropy
    entropy = 0.0
    for prob in probs:
        entropy -= prob * log2(prob)

    return entropy
956615
def _passphrase_callback(passphrase):
    '''
    
    '''
    def f(*args):
        return salt.utils.stringutils.to_bytes(passphrase)
    return f
1289302
def generate_entropy(strength, internal_entropy, external_entropy):
    '''
    
    '''
    if strength not in (128, 192, 256):
        raise Exception("Invalid strength")

    if not internal_entropy:
        raise Exception("Internal entropy is not provided")

    if len(internal_entropy) < 32:
        raise Exception("Internal entropy too short")

    if not external_entropy:
        raise Exception("External entropy is not provided")

    if len(external_entropy) < 32:
        raise Exception("External entropy too short")

    entropy = hashlib.sha256(internal_entropy + external_entropy).digest()
    entropy_stripped = entropy[:strength // 8]

    if len(entropy_stripped) * 8 != strength:
        raise Exception("Entropy length mismatch")

    return entropy_stripped
1267985
function entropy(str) {
    if (!str) return 0;
    return Math.round(str.length * (Math.log(alphabetSize(str)) / Math.log(2)));
}
222658
def passphrase_entropy(amount_w: int,
                       entropy_w: Union[int, float],
                       entropy_n: Union[int, float],
                       amount_n: int) -> float:
    """"""
    if not isinstance(amount_w, int):
        raise TypeError('amount_w can only be int')
    if not isinstance(entropy_w, (int, float)):
        raise TypeError('entropy_w can only be int or float')
    if not isinstance(entropy_n, (int, float)):
        raise TypeError('entropy_n can only be int or float')
    if not isinstance(amount_n, int):
        raise TypeError('amount_n can only be int')
    if amount_w < 0:
        raise ValueError('amount_w should be greater than 0')
    if entropy_w < 0:
        raise ValueError('entropy_w should be greater than 0')
    if entropy_n < 0:
        raise ValueError('entropy_n should be greater than 0')
    if amount_n < 0:
        raise ValueError('amount_n should be greater than 0')

    return float(amount_w * entropy_w + amount_n * entropy_n)
257461
def entropy(string):
    """"""
    p, lns = Counter(string), float(len(string))
    return -sum(count/lns * math.log(count/lns, 2) for count in p.values())
10020
function passphraseToKey(type, passphrase, salt)
  {
  debug('passphraseToKey', type, passphrase, salt);
  var nkey = keyBytes[type];

  if (!nkey)
    {
    var allowed = Object.keys(keyBytes);
    throw new TypeError('Unsupported type. Allowed: ' + allowed);
    }

  var niv = salt.length;
  var saltLen = 8;
  if (salt.length !== saltLen)
    salt = salt.slice(0, saltLen);
  var mds = 16;
  var addmd = false;
  var md_buf;
  var key = new Buffer(nkey);
  var keyidx = 0;

  while (true)
    {
    debug('loop nkey=%d mds=%d', nkey, mds);
    var c = crypto.createHash('md5');

    if (addmd)
      c.update(md_buf);
    else
      addmd = true;

    if (!Buffer.isBuffer(passphrase))
      c.update(passphrase, 'ascii');
    else
      c.update(passphrase);

    c.update(salt);
    md_buf = c.digest('buffer');

    var i = 0;
    while (nkey && i < mds)
      {
      key[keyidx++] = md_buf[i];
      nkey--;
      i++;
      }

    var steps = Math.min(niv, mds - i);
    niv -= steps;
    i += steps;

    if ((nkey == 0) && (niv == 0)) break;
    }

  return key
  }
497153
public function getMinimumEntropy($password, $matches)
    {
        $passwordLength = strlen($password);
        $entropyStack = [];
        // for the optimal sequence of matches up to k, holds the final match (match.end == k).
        // null means the sequence ends without a brute-force character.
        $backpointers = [];
        $bruteforceMatch = new Bruteforce($password, 0, $passwordLength - 1, $password);
        $charEntropy = log($bruteforceMatch->getCardinality(), 2);

        foreach (range(0, $passwordLength - 1) as $k) {
            // starting scenario to try and beat: adding a brute-force character to the minimum entropy sequence at k-1.
            $entropyStack[$k] = $this->prevValue($entropyStack, $k) + $charEntropy;
            $backpointers[$k] = null;
            foreach ($matches as $match) {
                if (!isset($match->begin) || $match->end !== $k) {
                    continue;
                }

                // See if entropy prior to match + entropy of this match is less than
                // the current minimum top of the stack.
                $candidateEntropy = $this->prevValue($entropyStack, $match->begin) + $match->getEntropy();
                if ($candidateEntropy <= $entropyStack[$k]) {
                    $entropyStack[$k] = $candidateEntropy;
                    $backpointers[$k] = $match;
                }
            }
        }

        // Walk backwards and decode the best sequence
        $matchSequence = [];
        $k = $passwordLength - 1;
        while ($k >= 0) {
            $match = $backpointers[$k];

            if ($match) {
                $matchSequence[] = $match;

                $k = $match->begin - 1;
            } else {
                --$k;
            }
        }
        $matchSequence = array_reverse($matchSequence);

        $s = 0;
        $matchSequenceCopy = [];
        // Handle subtrings that weren't matched as bruteforce match.
        foreach ($matchSequence as $match) {
            if ($match->begin - $s > 0) {
                $matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $match->begin - 1, $bruteforceMatch->getCardinality());
            }

            $s = $match->end + 1;
            $matchSequenceCopy[] = $match;
        }

        if ($s < $passwordLength) {
            $matchSequenceCopy[] = $this->makeBruteforceMatch($password, $s, $passwordLength - 1, $bruteforceMatch->getCardinality());
        }

        $this->matchSequence = $matchSequenceCopy;

        return $entropyStack[$passwordLength - 1];
    }
201659
def _load_words(self):
        """"""
        with open(self._words_file, 'r') as f:
            self._censor_list = [line.strip() for line in f.readlines()]
417312
def GeneratePassphrase(length=20):
  """"""
  valid_chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"
  valid_chars += "0123456789 ,-_&$#"
  return "".join(random.choice(valid_chars) for i in range(length))
37699
def calculate_shannon_entropy(self, data):
        
        if not data:  # pragma: no cover
            return 0

        entropy = 0
        for x in self.charset:
            p_x = float(data.count(x)) / len(data)
            if p_x > 0:
                entropy += - p_x * math.log(p_x, 2)

        return entropy
823307
def generate_words(numberofwords, wordlist, secure=None):
    """"""
    if not secure:
        chooser = random.choice
    else:
        chooser = random.SystemRandom().choice
    return [chooser(wordlist) for _ in range(numberofwords)]
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
246348
def _get_passwordkey(self):
        """"""

        sha = SHA256.new()
        sha.update(self.password.encode('utf-8'))
        return sha.digest()
377677
def normalize_password(text, encoding='utf-8'):
    '''
    '''
    path = percent_encode(text, encoding=encoding, encode_set=PASSWORD_ENCODE_SET)
    return uppercase_percent_encoding(path)