Python hashlib.pbkdf2_hmac() Examples

The following are 30 code examples of hashlib.pbkdf2_hmac(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module hashlib , or try the search function .
Example #1
Source File: test_hashlib.py    From ironpython2 with Apache License 2.0 6 votes vote down vote up
def test_pbkdf2_hmac(self):
        for digest_name, results in self.pbkdf2_results.items():
            for i, vector in enumerate(self.pbkdf2_test_vectors):
                password, salt, rounds, dklen = vector
                expected, overwrite_dklen = results[i]
                if overwrite_dklen:
                    dklen = overwrite_dklen
                out = hashlib.pbkdf2_hmac(
                    digest_name, password, salt, rounds, dklen)
                self.assertEqual(out, expected,
                                 (digest_name, password, salt, rounds, dklen)) 
Example #2
Source File: auth.py    From chalice-workshop with Apache License 2.0 6 votes vote down vote up
def get_jwt_token(username, password, record):
    actual = hashlib.pbkdf2_hmac(
        record['hash'],
        password,
        record['salt'].value,
        record['rounds']
    )
    expected = record['hashed'].value
    if hmac.compare_digest(actual, expected):
        now = datetime.datetime.utcnow()
        unique_id = str(uuid4())
        payload = {
            'sub': username,
            'iat': now,
            'nbf': now,
            'jti': unique_id,
            # NOTE: We can also add 'exp' if we want tokens to expire.
        }
        return jwt.encode(payload, _SECRET, algorithm='HS256')
    raise UnauthorizedError('Invalid password') 
Example #3
Source File: auth.py    From learn_python3_spider with MIT License 6 votes vote down vote up
def _hi(hash_name, data, salt, iterations):
            """A simple implementation of PBKDF2-HMAC."""
            mac = hmac.HMAC(data, None, getattr(hashlib, hash_name))

            def _digest(msg, mac=mac):
                """Get a digest for msg."""
                _mac = mac.copy()
                _mac.update(msg)
                return _mac.digest()

            from_bytes = _from_bytes
            to_bytes = _to_bytes

            _u1 = _digest(salt + b'\x00\x00\x00\x01')
            _ui = from_bytes(_u1, 'big')
            for _ in range(iterations - 1):
                _u1 = _digest(_u1)
                _ui ^= from_bytes(_u1, 'big')
            return to_bytes(_ui, mac.digest_size, 'big') 
Example #4
Source File: mega.py    From mega.py with Apache License 2.0 6 votes vote down vote up
def _login_user(self, email, password):
        logger.info('Logging in user...')
        email = email.lower()
        get_user_salt_resp = self._api_request({'a': 'us0', 'user': email})
        user_salt = None
        try:
            user_salt = base64_to_a32(get_user_salt_resp['s'])
        except KeyError:
            # v1 user account
            password_aes = prepare_key(str_to_a32(password))
            user_hash = stringhash(email, password_aes)
        else:
            # v2 user account
            pbkdf2_key = hashlib.pbkdf2_hmac(hash_name='sha512',
                                             password=password.encode(),
                                             salt=a32_to_str(user_salt),
                                             iterations=100000,
                                             dklen=32)
            password_aes = str_to_a32(pbkdf2_key[:16])
            user_hash = base64_url_encode(pbkdf2_key[-16:])
        resp = self._api_request({'a': 'us', 'user': email, 'uh': user_hash})
        if isinstance(resp, int):
            raise RequestError(resp)
        self._login_process(resp, password_aes) 
Example #5
Source File: utils.py    From zentral with Apache License 2.0 6 votes vote down vote up
def build_password_hash_dict(password):
    # see https://developer.apple.com/documentation/devicemanagement/setautoadminpasswordcommand/command
    # for the compatibility
    password = password.encode("utf-8")
    salt = bytearray(random.getrandbits(8) for i in range(32))
    iterations = 39999
    # see https://github.com/micromdm/micromdm/blob/master/pkg/crypto/password/password.go macKeyLen !!!
    # Danke github.com/groob !!!
    dklen = 128

    dk = hashlib.pbkdf2_hmac("sha512", password, salt, iterations, dklen=dklen)
    return {
        "SALTED-SHA512-PBKDF2": {
            "entropy": base64.b64encode(dk).decode("ascii").strip(),
            "salt": base64.b64encode(salt).decode("ascii").strip(),
            "iterations": iterations
        }
    } 
Example #6
Source File: pwhash.py    From vj4 with GNU Affero General Public License v3.0 6 votes vote down vote up
def hash_vj4(password: str, salt: str):
  dk = hashlib.pbkdf2_hmac('sha256', password.encode(), salt.encode(), 100000)
  return _HASH_TYPE_VJ4 + '|' + binascii.hexlify(dk).decode() 
Example #7
Source File: auth.py    From chalice-workshop with Apache License 2.0 6 votes vote down vote up
def get_jwt_token(username, password, record):
    actual = hashlib.pbkdf2_hmac(
        record['hash'],
        password,
        record['salt'].value,
        record['rounds']
    )
    expected = record['hashed'].value
    if hmac.compare_digest(actual, expected):
        now = datetime.datetime.utcnow()
        unique_id = str(uuid4())
        payload = {
            'sub': username,
            'iat': now,
            'nbf': now,
            'jti': unique_id,
            # NOTE: We can also add 'exp' if we want tokens to expire.
        }
        return jwt.encode(payload, _SECRET, algorithm='HS256')
    raise UnauthorizedError('Invalid password') 
Example #8
Source File: crypto.py    From GTDWeb with GNU General Public License v2.0 6 votes vote down vote up
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
        """
        Implements PBKDF2 with the same API as Django's existing
        implementation, using the stdlib.

        This is used in Python 2.7.8+ and 3.4+.
        """
        if digest is None:
            digest = hashlib.sha256
        if not dklen:
            dklen = None
        password = force_bytes(password)
        salt = force_bytes(salt)
        return hashlib.pbkdf2_hmac(
            digest().name, password, salt, iterations, dklen) 
Example #9
Source File: onepass.py    From opvault with GNU General Public License v3.0 6 votes vote down vote up
def _derive_keys(master_password, salt, iterations):
        derived_key = hashlib.pbkdf2_hmac(
            'sha512', master_password, salt, iterations)
        key = derived_key[:32]
        hmac_key = derived_key[32:64]

        return key, hmac_key 
Example #10
Source File: helpers.py    From specter-desktop with MIT License 6 votes vote down vote up
def hash_password(password):
    """Hash a password for storing."""
    salt = binascii.b2a_base64(hashlib.sha256(os.urandom(60)).digest()).strip()
    pwdhash = binascii.b2a_base64(hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 10000)).strip().decode()
    return { 'salt': salt.decode(), 'pwdhash': pwdhash } 
Example #11
Source File: helpers.py    From specter-desktop with MIT License 6 votes vote down vote up
def verify_password(stored_password, provided_password):
    """Verify a stored password against one provided by user"""
    pwdhash = hashlib.pbkdf2_hmac('sha256', 
                                  provided_password.encode('utf-8'), 
                                  stored_password['salt'].encode(), 
                                  10000)
    return pwdhash == binascii.a2b_base64(stored_password['pwdhash']) 
Example #12
Source File: mnemonic_utils.py    From ethereum-mnemonic-utils with MIT License 6 votes vote down vote up
def mnemonic_to_bip39seed(mnemonic, passphrase):
    """ BIP39 seed from a mnemonic key.
        Logic adapted from https://github.com/trezor/python-mnemonic. """
    mnemonic = bytes(mnemonic, 'utf8')
    salt = bytes(BIP39_SALT_MODIFIER + passphrase, 'utf8')
    return hashlib.pbkdf2_hmac('sha512', mnemonic, salt, BIP39_PBKDF2_ROUNDS) 
Example #13
Source File: auth.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def _hi(hash_name, data, salt, iterations):
            """A simple implementation of PBKDF2-HMAC."""
            mac = hmac.HMAC(data, None, getattr(hashlib, hash_name))

            def _digest(msg, mac=mac):
                """Get a digest for msg."""
                _mac = mac.copy()
                _mac.update(msg)
                return _mac.digest()

            from_bytes = _from_bytes
            to_bytes = _to_bytes

            _u1 = _digest(salt + b'\x00\x00\x00\x01')
            _ui = from_bytes(_u1, 'big')
            for _ in range(iterations - 1):
                _u1 = _digest(_u1)
                _ui ^= from_bytes(_u1, 'big')
            return to_bytes(_ui, mac.digest_size, 'big') 
Example #14
Source File: util.py    From TabPy with MIT License 6 votes vote down vote up
def hash_password(username, pwd):
    """
    Hashes password using PKDBF2 method:
    hash = PKDBF2('sha512', pwd, salt=username, 10000)

    Parameters
    ----------
    username : str
        User name (login). Used as salt for hashing.
        User name is lowercased befor being used in hashing.
        Salt is formatted as '_$salt@tabpy:<username>$_' to
        guarantee there's at least 16 characters.

    pwd : str
        Password to hash.

    Returns
    -------
    str
        Sting representation (hexidecimal) for PBKDF2 hash
        for the password.
    """
    salt = f"_$salt@tabpy:{username.lower()}$_"

    hash = pbkdf2_hmac(
        hash_name="sha512", password=pwd.encode(), salt=salt.encode(), iterations=10000
    )
    return binascii.hexlify(hash).decode() 
Example #15
Source File: crypto.py    From bioforum with MIT License 6 votes vote down vote up
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
    """Return the hash of password using pbkdf2."""
    if digest is None:
        digest = hashlib.sha256
    if not dklen:
        dklen = None
    password = force_bytes(password)
    salt = force_bytes(salt)
    return hashlib.pbkdf2_hmac(digest().name, password, salt, iterations, dklen) 
Example #16
Source File: raiwalletbot.py    From NanoWalletBot with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def password_check(update, password):
	user_id = update.message.from_user.id
	password_hash = mysql_check_password(user_id)
	if (password_hash is not False):
		dk = '0000'
		try:
			if (len(password_hash) == 128):
				# New Scrypt KDF
				dk = hashlib.scrypt(password.encode('utf-8'), salt=(hashlib.sha3_224(user_id.to_bytes(6, byteorder='little')).hexdigest()+salt).encode('utf-8'), n=2**15, r=8, p=1, maxmem=2**26, dklen=64)
			else:
				# Old PBKDF2 KDF
				dk = hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt.encode(), pbkdf2_iterations)
		except UnicodeEncodeError as e:
			text_reply(update, lang(user_id, 'encoding_error'))
			sleep(0.5)
		hex = binascii.hexlify(dk).decode()
		if (hex == password_hash):
			valid = True
		else:
			valid = False
			logging.info('Wrong password for user {0}. Expected: {1}, given: {2}'.format(user_id, password_hash, hex))
	else:
		valid = True
	return valid 
Example #17
Source File: bip39_mnemonic.py    From pybtc with GNU General Public License v3.0 6 votes vote down vote up
def mnemonic_to_seed(mnemonic, passphrase="", hex=True):
    """
    Converting mnemonic words string to seed for uses in key derivation (BIP-0032).

    :param str mnemonic: mnemonic words string (space separated)
    :param str passphrase: (optional) passphrase to get ability use 2FA approach for 
                          creating seed, by default empty string.
    :param boolean hex: return HEX encoded string result flag, by default True.
    :return: HEX encoded or bytes string.
    """
    if not isinstance(mnemonic, str):
        raise TypeError("mnemonic should be string")
    if not isinstance(passphrase, str):
        raise TypeError("mnemonic should be string")

    seed = hashlib.pbkdf2_hmac('sha512', mnemonic.encode(), ("mnemonic"+passphrase).encode(), 2048)
    return seed if not hex else seed.hex() 
Example #18
Source File: andotp_decrypt.py    From andOTP-decrypt with MIT License 6 votes vote down vote up
def decrypt_aes_new_format(password, input_file, debug=False):
    input_bytes = None
    with open(input_file, 'rb') as f:
        input_bytes = f.read()

    # Raw data structure is iterations[:4] + salt[4:16] + data[16:]
    iterations = struct.unpack(">I", input_bytes[:4])[0]
    salt       = input_bytes[4:16]
    data       = input_bytes[16:]
    pbkdf2_key = hashlib.pbkdf2_hmac('sha1', password, salt, iterations, 32)
    if debug:
        print("Iterations: %s" % iterations)
        print("Salt: %s" % bytes2Hex(salt))
        print("Pbkdf2 key: %s" % bytes2Hex(pbkdf2_key))

    return decode(pbkdf2_key, data, debug) 
Example #19
Source File: bip39.py    From btclib with MIT License 6 votes vote down vote up
def seed_from_mnemonic(
    mnemonic: Mnemonic, passphrase: str, verify_checksum=True
) -> bytes:
    """Return the seed from the provided BIP39 mnemonic sentence.

    The mnemonic checksum verification can be skipped if needed.
    """

    if verify_checksum:
        entropy_from_mnemonic(mnemonic)

    hf_name = "sha512"
    # clean up mnemonic from spurious whitespaces
    password = " ".join(mnemonic.split()).encode()
    salt = ("mnemonic" + passphrase).encode()
    iterations = 2048
    dksize = 64
    return pbkdf2_hmac(hf_name, password, salt, iterations, dksize) 
Example #20
Source File: passwd.py    From aiohttp-json-rpc with Apache License 2.0 6 votes vote down vote up
def _create_user(self, username, password, salt=None, rounds=100000,
                     permissions=None):

        if username in self.user:
            return False

        salt = salt or os.urandom(16)

        if not type(password) == bytes:
            password = password.encode()

        password_hash = hashlib.pbkdf2_hmac('sha256', password, salt, rounds)

        self.user[username] = {
            'password_hash': password_hash,
            'salt': salt,
            'rounds': rounds,
            'permissions': permissions or []
        }

        self.write()

        return True 
Example #21
Source File: passwd.py    From aiohttp-json-rpc with Apache License 2.0 6 votes vote down vote up
def _set_password(self, username, password, salt=None, rounds=100000,
                      old_password=''):

        if old_password:
            if not self._login(username, old_password)[0]:
                return False

        salt = salt or os.urandom(16)

        if not type(password) == bytes:
            password = password.encode()

        password_hash = hashlib.pbkdf2_hmac('sha256', password, salt, rounds)

        self.user[username]['password_hash'] = password_hash
        self.user[username]['salt'] = salt
        self.user[username]['rounds'] = rounds

        return True 
Example #22
Source File: crypto.py    From python with Apache License 2.0 5 votes vote down vote up
def pbkdf2(password, salt, iterations, dklen=0, digest=None):
        """
        Implements PBKDF2 with the same API as Django's existing
        implementation, using the stdlib.

        This is used in Python 2.7.8+ and 3.4+.
        """
        if digest is None:
            digest = hashlib.sha256
        if not dklen:
            dklen = None
        password = force_bytes(password)
        salt = force_bytes(salt)
        return hashlib.pbkdf2_hmac(
            digest().name, password, salt, iterations, dklen) 
Example #23
Source File: crypter.py    From ctSESAM-python-memorizing with GNU General Public License v3.0 5 votes vote down vote up
def create_key(password, salt, iterations=1024):
        """
        Creates a key for encrypting/decrypting settings.

        :param password: this is the kgk
        :type password: bytes
        :param salt: the salt2
        :type salt: bytes
        :param iterations: an iteration count
        :type iterations: int
        :return: a key
        :rtype: bytes
        """
        return pbkdf2_hmac('sha256', password, salt, iterations) 
Example #24
Source File: user.py    From slim with zlib License 5 votes vote down vote up
def gen_password_and_salt(cls, password_text):
        """ 生成加密后的密码和盐 """
        salt = os.urandom(32)
        dk = hashlib.pbkdf2_hmac(
            config.PASSWORD_HASH_FUNC_NAME,
            password_text.encode('utf-8'),
            salt,
            config.PASSWORD_HASH_ITERATIONS,
        )
        return {'password': dk, 'salt': salt} 
Example #25
Source File: security.py    From scylla with Apache License 2.0 5 votes vote down vote up
def pbkdf2_bin(
    data, salt, iterations=DEFAULT_PBKDF2_ITERATIONS, keylen=None, hashfunc=None
):
    """Returns a binary digest for the PBKDF2 hash algorithm of `data`
    with the given `salt`. It iterates `iterations` times and produces a
    key of `keylen` bytes. By default, SHA-256 is used as hash function;
    a different hashlib `hashfunc` can be provided.

    .. versionadded:: 0.9

    :param data: the data to derive.
    :param salt: the salt for the derivation.
    :param iterations: the number of iterations.
    :param keylen: the length of the resulting key.  If not provided
                   the digest size will be used.
    :param hashfunc: the hash function to use.  This can either be the
                     string name of a known hash function or a function
                     from the hashlib module.  Defaults to sha256.
    """
    if not hashfunc:
        hashfunc = "sha256"

    data = to_bytes(data)
    salt = to_bytes(salt)

    if callable(hashfunc):
        _test_hash = hashfunc()
        hash_name = getattr(_test_hash, "name", None)
    else:
        hash_name = hashfunc
    return hashlib.pbkdf2_hmac(hash_name, data, salt, iterations, keylen) 
Example #26
Source File: ipcypher.py    From django-GDPR with MIT License 5 votes vote down vote up
def derive_key(key: str):
    """
    PBKDF2(SHA1, Password, 'ipcipheripcipher', 50000, 16)
    """

    return pbkdf2_hmac('sha1', bytes(key, encoding="utf-8"), bytes('ipcipheripcipher', encoding='utf-8'), 50000, 16) 
Example #27
Source File: crypter.py    From ctSESAM-python-memorizing with GNU General Public License v3.0 5 votes vote down vote up
def createIvKey(password, salt, iterations=32768):
        """
        Creates a key for encrypting/decrypting kgk blocks.

        :param password: this is the kgk
        :type password: bytes
        :param salt: the salt2
        :type salt: bytes
        :param iterations: an iteration count
        :type iterations: int
        :return: a key
        :rtype: bytes
        """
        return pbkdf2_hmac('sha384', password, salt, iterations) 
Example #28
Source File: password_generator.py    From ctSESAM-python-memorizing with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, domain, username, kgk, salt="pepper".encode('utf-8'), iterations=4096):
        start_value = domain.encode('utf-8') + username.encode('utf-8') + kgk
        if iterations <= 0:
            print("Iteration count was below 1. Hashing 4096 times instead.")
            iterations = 4096
        self.hash_value = pbkdf2_hmac('sha512', start_value, salt, iterations) 
Example #29
Source File: user.py    From slim with zlib License 5 votes vote down vote up
def _auth_base(self, password_text):
        """
        已获取了用户对象,进行密码校验
        :param password_text:
        :return:
        """
        dk = hashlib.pbkdf2_hmac(
            config.PASSWORD_HASH_FUNC_NAME,
            password_text.encode('utf-8'),
            get_bytes_from_blob(self.salt),
            config.PASSWORD_HASH_ITERATIONS
        )

        if get_bytes_from_blob(self.password) == get_bytes_from_blob(dk):
            return self 
Example #30
Source File: _utils.py    From eth-account with MIT License 5 votes vote down vote up
def pbkdf2_hmac_sha512(passcode: str, salt: str) -> bytes:
    return hashlib.pbkdf2_hmac(
        "sha512",
        passcode.encode("utf-8"),
        salt.encode("utf-8"),
        PBKDF2_ROUNDS,
    )