Returns the result of the Password-Based Key Derivation Function 2 with
       a single iteration (i.e. count = 1).

       prf - a psuedorandom function

       See http://en.wikipedia.org/wiki/PBKDF2
428318
def pbkdf2_single(password, salt, key_length, prf):
    '''
    '''

    block_number = 0
    result = b''

    # The iterations
    while len(result) < key_length:
        block_number += 1
        result += prf(password, salt + struct.pack('>L', block_number))

    return result[:key_length]
1007914
def __kdf(self, secret_key_material):
        

        salt = b"\x00" * self.__hash_function().digest_size

        if self.__curve == "25519":
            input_key_material = b"\xFF" * 32
        if self.__curve == "448":
            input_key_material = b"\xFF" * 57

        input_key_material += secret_key_material

        hkdf = HKDF(
            algorithm=self.__hash_function(),
            length=32,
            salt=salt,
            info=self.__info_string,
            backend=self.__class__.CRYPTOGRAPHY_BACKEND
        )

        return hkdf.derive(input_key_material)
694239
def pwgen(length=None):
    """"""
    if length is None:
        # A random length is ok to use a weak PRNG
        length = random.choice(range(35, 45))
    alphanumeric_chars = [
        l for l in (string.ascii_letters + string.digits)
        if l not in 'l0QD1vAEIOUaeiou']
    # Use a crypto-friendly PRNG (e.g. /dev/urandom) for making the
    # actual password
    random_generator = random.SystemRandom()
    random_chars = [
        random_generator.choice(alphanumeric_chars) for _ in range(length)]
    return(''.join(random_chars))
633526
public function pbkdf2($p, $s, $c, $dkLen, $a = 'sha256') {
    $hLen = strlen(hash($a, null, true)); /* Hash length. */
    $l    = ceil($dkLen / $hLen);         /* Length in blocks of derived key. */
    $dk   = '';                           /* Derived key. */

    /* Step 1. Check dkLen. */
    if($dkLen > (2^32-1) * $hLen) {
      throw new \phpSec\Exception\GeneralSecurityException('Derived key too long');
      return false;
    }

    for ($block = 1; $block<=$l; $block ++) {
      /* Initial hash for this block. */
      $ib = $b = hash_hmac($a, $s . pack('N', $block), $p, true);
      /* Do block iterations. */
      for ($i = 1; $i<$c; $i ++) {
        /* XOR iteration. */
        $ib ^= ($b = hash_hmac($a, $b, $p, true));
      }
      /* Append iterated block. */
      $dk .= $ib;
    }
    /* Returned derived key. */
    return substr($dk, 0, $dkLen);
  }
724495
def encrypt(self, password, kdf=None, iterations=None):
        '''
        
        '''
        return self._publicapi.encrypt(self.privateKey, password, kdf=kdf, iterations=iterations)
130181
protected function _f(string $P, string $S, int $c, int $i): string
    {
        // compute U_1
        $U = $this->_prf->compute($P, $S . pack("N", $i));
        $result = $U;
        for ($x = 2; $x <= $c; ++$x) {
            // U_x receives feedback from U_{x-1}
            $U_x = $this->_prf->compute($P, $U);
            // add to XOR-sum
            $result ^= $U_x;
            $U = $U_x;
        }
        return $result;
    }
931648
function _gpfSkipPad (text, pad) {
    var idx = 0;
    while (idx < text.length && -1 !== pad.indexOf(text.charAt(idx))) {
        ++idx;
    }
    return idx;
}
1300458
def crypto_sign_keypair():
    
    pk = ffi.new("unsigned char[]", crypto_sign_PUBLICKEYBYTES)
    sk = ffi.new("unsigned char[]", crypto_sign_SECRETKEYBYTES)

    rc = lib.crypto_sign_keypair(pk, sk)
    ensure(rc == 0,
           'Unexpected library error',
           raising=exc.RuntimeError)

    return (
        ffi.buffer(pk, crypto_sign_PUBLICKEYBYTES)[:],
        ffi.buffer(sk, crypto_sign_SECRETKEYBYTES)[:],
    )
815408
def kdf_iterations(self):
        

        encryption_algo = self['algorithm'].native

        if encryption_algo == 'pbes2':
            return self['parameters']['key_derivation_func']['parameters']['iteration_count'].native

        if encryption_algo.find('.') == -1:
            if encryption_algo.find('_') != -1:
                return self['parameters']['iterations'].native

            raise ValueError(unwrap(
                '''
                Encryption algorithm "%s" does not have a registered key
                derivation function
                ''',
                encryption_algo
            ))

        raise ValueError(unwrap(
            '''
            Unrecognized encryption algorithm "%s", can not determine key
            derivation iterations
            ''',
            encryption_algo
        ))
1248023
def publickey_unsafe(sk):
    
    h = H(sk)
    a = 2 ** (b - 2) + sum(2 ** i * bit(h, i) for i in range(3, b - 2))
    A = scalarmult_B(a)
    return encodepoint(A)
294897
def password_generator(length):
    
    return ''.join(random.choice(string.ascii_lowercase + string.digits)
                   for _ in range(length))
446096
private int computeSimpleCredsHashCode( SimpleCredentials c ) {
        String userID = c.getUserID();
        char[] password = c.getPassword();
        Map<String, Object> m = getAttributeMap(c);
        final int prime = 31;
        int result = 1;
        result = prime * result + ((userID == null) ? 0 : userID.hashCode());
        for (int i = 0; i < password.length; i++) {
            result = prime * result + password[i];
        }
        result = prime * result + ((m == null) ? 0 : m.hashCode());
        return result;
    }
781628
def psq2(d1, d2):
    
    d1, d2 = flatten(d1), flatten(d2)

    def f(p):
        return sum((p ** 2) * np.nan_to_num(np.log(p * len(p))))

    return abs(f(d1) - f(d2))
829809
def generate_key(k, seed=None):
    

    def modinv(a, m):
        """calculate the inverse of a mod m
        that is, find b such that (a * b) % m == 1"""
        b = 1
        while not (a * b) % m == 1:
            b += 1
        return b

    def gen_prime(k, seed=None):
        """generate a prime with k bits"""

        def is_prime(num):
            if num == 2:
                return True
            for i in range(2, int(num ** 0.5) + 1):
                if num % i == 0:
                    return False
            return True

        random.seed(seed)
        while True:
            key = random.randrange(int(2 ** (k - 1)), int(2 ** k))
            if is_prime(key):
                return key

    # size in bits of p and q need to add up to the size of n
    p_size = k / 2
    q_size = k - p_size
    
    e = gen_prime(k, seed)  # in many cases, e is also chosen to be a small constant
    
    while True:
        p = gen_prime(p_size, seed)
        if p % e != 1:
            break
    
    while True:
        q = gen_prime(q_size, seed)
        if q % e != 1:
            break
    
    n = p * q
    l = (p - 1) * (q - 1)  # calculate totient function
    d = modinv(e, l)
    
    return int(n), int(e), int(d)
665830
def _get_public_key_count(self):
        """"""
        index = len(self._public_keys)
        for authentication in self._authentications:
            if authentication.is_public_key():
                index += 1
        return index
718132
async function decryptPBES1(decoded, passphrase){
  // pbkdf1
  const pBuffer = jseu.encoder.stringToArrayBuffer(passphrase);
  const salt = new Uint8Array(decoded.encryptionAlgorithm.parameters.salt);
  const hash = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].hash;
  const iterationCount = decoded.encryptionAlgorithm.parameters.iterationCount.toNumber();
  const keyIv = await pbkdf.pbkdf1(pBuffer, salt, iterationCount, 16, hash);
  const key = keyIv.slice(0, 8);
  const iv = keyIv.slice(8, 16);

  // decryption
  const encrypt = params.passwordBasedEncryptionSchemes[decoded.encryptionAlgorithm.algorithm].encrypt;
  let out;
  // TODO: Other Encryption Scheme
  if(encrypt === 'DES-CBC') {
    const CBC = des.CBC.instantiate(des.DES);
    const ct = CBC.create({type: 'decrypt', key, iv});
    out = Buffer.from(ct.update(decoded.encryptedData).concat(ct.final()));
  }
  else throw new Error('UnsupportedEncryptionAlgorithm');

  return OneAsymmetricKey.decode(out, 'der');
}
844480
function _gpfPow2 (n) {
    var result = _gpfPow2[n];
    if (result) {
        return result;
    }
    result = _gpfComputePow2(n);
    _gpfPow2[n] = result;
    return result;
}