本文整理汇总了Python中hashlib.pbkdf2_hmac方法的典型用法代码示例。如果您正苦于以下问题:Python hashlib.pbkdf2_hmac方法的具体用法?Python hashlib.pbkdf2_hmac怎么用?Python hashlib.pbkdf2_hmac使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类hashlib
的用法示例。
在下文中一共展示了hashlib.pbkdf2_hmac方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _hi
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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')
示例2: mnemonic_to_seed
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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()
示例3: seed_from_mnemonic
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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)
示例4: _create_user
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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
示例5: _set_password
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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
示例6: _login_user
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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)
示例7: build_password_hash_dict
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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
}
}
示例8: decrypt_aes_new_format
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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)
示例9: password_check
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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
示例10: get_jwt_token
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
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')
示例11: _round_function
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
def _round_function(i: int, passphrase: bytes, e: int, salt: bytes, r: bytes) -> bytes:
"""The round function used internally by the Feistel cipher."""
return hashlib.pbkdf2_hmac(
"sha256",
bytes([i]) + passphrase,
salt + r,
(BASE_ITERATION_COUNT << e) // ROUND_COUNT,
dklen=len(r),
)
示例12: pbkdf2_hmac_sha512
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
def pbkdf2_hmac_sha512(passcode: str, salt: str) -> bytes:
return hashlib.pbkdf2_hmac(
"sha512",
passcode.encode("utf-8"),
salt.encode("utf-8"),
PBKDF2_ROUNDS,
)
示例13: hashToken
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
def hashToken(self,token):
return hexlify(pbkdf2_hmac('sha256',token, sha1('CBoePassword').digest(), 100000))
示例14: hashToken
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
def hashToken(self,token):
return hexlify(pbkdf2_hmac( 'sha256',
token.encode('utf-8'),
sha1( 'CBoePassword'.encode('utf-8')).digest(),
100000))
示例15: pbkdf2sha512
# 需要导入模块: import hashlib [as 别名]
# 或者: from hashlib import pbkdf2_hmac [as 别名]
def pbkdf2sha512(password: bytes, salt: bytes, iterations: int):
return hashlib.pbkdf2_hmac('sha512', password, salt, iterations)