我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用hashlib.pbkdf2_hmac()。
def generate(password): '''Generate a ShadowHashData structure as used by macOS 10.8+''' iterations = arc4random.randrange(30000, 50000) salt = make_salt(32) keylen = 128 try: entropy = hashlib.pbkdf2_hmac( 'sha512', password, salt, iterations, dklen=keylen) except AttributeError: # old Python, do it a different way entropy = pbkdf2.pbkdf2_bin( password, salt, iterations=iterations, keylen=keylen, hashfunc=hashlib.sha512) data = {'SALTED-SHA512-PBKDF2': {'entropy': buffer(entropy), 'iterations': iterations, 'salt': buffer(salt)}, } return plistutils.write_plist(data, plist_format='binary')
def mnemonic_to_seed(mnemonic_phrase,passphrase=u''): try: from hashlib import pbkdf2_hmac def pbkdf2_hmac_sha256(password,salt,iters=2048): return pbkdf2_hmac(hash_name='sha512',password=password,salt=salt,iterations=iters) except: try: from Crypto.Protocol.KDF import PBKDF2 from Crypto.Hash import SHA512,HMAC def pbkdf2_hmac_sha256(password,salt,iters=2048): return PBKDF2(password=password,salt=salt,dkLen=64,count=iters,prf=lambda p,s: HMAC.new(p,s,SHA512).digest()) except: try: from pbkdf2 import PBKDF2 import hmac def pbkdf2_hmac_sha256(password,salt,iters=2048): return PBKDF2(password,salt, iterations=iters, macmodule=hmac, digestmodule=hashlib.sha512).read(64) except: raise RuntimeError("No implementation of pbkdf2 was found!") return pbkdf2_hmac_sha256(password=mnemonic_phrase,salt='mnemonic'+passphrase)
def chrome_process(safe_storage_key, loginData): iv = ''.join(('20',) * 16) #salt, iterations, iv, size - https://cs.chromium.org/chromium/src/components/os_crypt/os_crypt_mac.mm key = hashlib.pbkdf2_hmac('sha1', safe_storage_key, b'saltysalt', 1003)[:16] copypath = tempfile.mkdtemp() #work around for locking DB dbcopy = protected_file_reader(loginData) #again, shouldnt matter because we only can decrypt DBs with keys with open('%s/chrome' % copypath, 'wb') as content: content.write(dbcopy) #if chrome is open, the DB will be locked, so get around by making a temp copy database = sqlite3.connect('%s/chrome' % copypath) sql = 'select username_value, password_value, origin_url from logins' decryptedList = [] with database: for user, encryptedPass, url in database.execute(sql): if user == "" or (encryptedPass[:3] != b'v10'): #user will be empty if they have selected "never" store password continue else: urlUserPassDecrypted = (url.encode('ascii', 'ignore'), user.encode('ascii', 'ignore'), chrome_decrypt(encryptedPass, iv, key=key).encode('ascii', 'ignore')) decryptedList.append(urlUserPassDecrypted) shutil.rmtree(copypath) return decryptedList
def supported_by_hashlib_pbkdf2(self): """helper to detect if hash is supported by hashlib.pbkdf2_hmac()""" if not _stdlib_pbkdf2_hmac: return None try: _stdlib_pbkdf2_hmac(self.name, b"p", b"s", 1) return True except ValueError: # "unsupported hash type" return False #========================================================================= # eoc #========================================================================= #============================================================================= # hmac utils #============================================================================= #: translation tables used by compile_hmac()
def pbkdf2(password, salt, iterations, dklen=0, digest=None): """ Implements PBKDF2 using the stdlib. This is used in Python 2.7.8+ and 3.4+. HMAC+SHA256 is used as the default pseudo random function. As of 2014, 100,000 iterations was the recommended default which took 100ms on a 2.7Ghz Intel i7 with an optimized implementation. This is probably the bare minimum for security given 1000 iterations was recommended in 2001. """ if digest is None: digest = hashlib.sha1 if not dklen: dklen = None password = bytes_(password) salt = bytes_(salt) return hashlib.pbkdf2_hmac( digest().name, password, salt, iterations, dklen)
def encrypt(password='password', salt=None): """ Return SHA1 hexdigest of a password (optionally salted with a string). """ if not salt: salt = str(datetime.utcnow()) try: # available for python 2.7.8 and python 3.4+ dk = hashlib.pbkdf2_hmac('sha1', password.encode(), salt.encode(), 100000) hexdigest = binascii.hexlify(dk).decode('utf-8') except AttributeError: # see https://pymotw.com/2/hashlib/ # see https://docs.python.org/release/2.5/lib/module-hashlib.html dk = hashlib.sha1() dk.update(password.encode() + salt.encode()) hexdigest = dk.hexdigest() return hexdigest
def generate_key_material(pre_shared_key): #generate symmetric key enc_salt = gen_message_salt() if not enc_salt: logging.error('Unable to generate message salt ; Exiting') return False enc_derived_key = hashlib.pbkdf2_hmac('sha256', pre_shared_key, enc_salt, 5000000) #get the filename real_gist_file_name = gen_gist_file_name() if not real_gist_file_name: logging.error('Unable to generate filename for GIST upload ; Exiting') return False #the first 32-charcters are the iv bytes enc_iv = real_gist_file_name[0:32].decode("hex") return enc_derived_key, enc_salt, enc_iv, real_gist_file_name
def getUser(self, username, password): # Query met parameters sqlQuery = "SELECT pwd_hash, pwd_salt FROM tbl_users WHERE username = '{param1}'" # Combineren van de query en parameter sqlCommand = sqlQuery.format(param1=username) self.__cursor.execute(sqlCommand) result = self.__cursor.fetchone() if not result: return False db_hash_string = result[0] db_salt_string = result[1] pwd_bytes = password db_salt_bytes = binascii.unhexlify(db_salt_string) hash_bytes = hashlib.pbkdf2_hmac('sha256', pwd_bytes, db_salt_bytes, 100000) hash_string = binascii.hexlify(hash_bytes).decode('utf-8') self.__cursor.close() return hash_string == db_hash_string
def pw_ok(s1, s2): """ Returns True if pw(s1) == s2. """ _, f, n, k, s = s2.split(':') s1 = hashlib.pbkdf2_hmac(f, b(s1)[:1024], b(k), int(n)) s1 = binascii.hexlify(s1) eq = True for ch1, ch2 in zip(s1, b(s)): eq = ch1 == ch2 # contstant-time comparison return eq # print(pw_ok('1234', pw('1234'))) ##### ML ########################################################################################## #---- MODEL -------------------------------------------------------------------------------------- # The Model base class is inherited by Perceptron, Bayes, ...
def generateKey(self, key, salt): # 2 Iterations of PBKDF2 SHA256 return hashlib.pbkdf2_hmac('sha256', key, salt, 2)
def hash_password(password: str, salt: Optional[bytes] = None) -> HashAndSalt: pepper = b'alchemists discovered that gold came from earth air fire and water' salt = salt or secrets.token_bytes(16) salted_pass = salt + password.encode('utf-8') return hashlib.pbkdf2_hmac('sha512', salted_pass, pepper, 100000), salt
def _load_dkey(self): """ Load derived key from existing stash file. """ with open(self._path,'r',encoding='ascii') as fr: try: outer_data = json.load(fr) except json.decoder.JSONDecodeError: raise SSError("Invalid stash file structure") try: validate(outer_data,OUTER_SCHEMA) except ValidationError: raise SSError("Invalid outer schema") self._hash = outer_data['hash'] self._salt = hex_str_to_bytes(outer_data['salt']) self._iterations = outer_data['iterations'] # Derive key from password: dk = pbkdf2_hmac(self._hash, self._password, self._salt, self._iterations, nacl.secret.SecretBox.KEY_SIZE) self._box = nacl.secret.SecretBox(dk)
def _initialize_stash(self): """ Create an empty stash at self._path with password self._password """ outer_data = { 'hash': self._default_hash, 'salt': bytes_to_hex_str(os.urandom(self._default_salt_len)), 'iterations': self._default_num_iterations, } # Derive key from password: dk = pbkdf2_hmac(outer_data['hash'], self._password, hex_str_to_bytes(outer_data['salt']), outer_data['iterations'], nacl.secret.SecretBox.KEY_SIZE ) if len(dk) < nacl.secret.SecretBox.KEY_SIZE: raise SSCryptoError("Derived key is not long enough") box = nacl.secret.SecretBox(dk) empty_store = json.dumps({}).encode('utf-8') nonce = nacl.utils.random(nacl.secret.SecretBox.NONCE_SIZE) outer_data['enc_blob'] = bytes_to_hex_str( box.encrypt(empty_store,nonce)) with open(self._path,'w',encoding='ascii') as fw: json.dump(outer_data,fw)
def _hi(data, salt, iterations): return pbkdf2_hmac('sha1', data, salt, iterations)
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)
def generateKeys(password, nonce): resultBytes = [] for i in range(1, 5): currNonce = nonce + bytearray([i]) resultBytes.append(KeyStream.pbkdf2(password, currNonce, 2, 20)) return resultBytes #@staticmethod ##use if drop python-2.6 support #def pbkdf2( password, salt, itercount, keylen): # return bytearray(hashlib.pbkdf2_hmac('sha1', password, salt, itercount, keylen))
def hash_password(password, salt): hashed = pbkdf2_hmac( c.PKCS_HASH_NAME, password.encode(), salt.encode(), c.PKCS_ITERATION_COUNT ) return hexlify(hashed).decode('ascii')
def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): hashfunc = hashfunc or sha1 hmac = hashlib.pbkdf2_hmac(hashfunc().name, to_bytes(data), to_bytes(salt), iterations, keylen) return binascii.hexlify(hmac)
def generate(self): user_pass = raw_input("Enter your keyring password: ") password = hex(random.getrandbits(512 * 8))[2:-1] salt = hex(random.getrandbits(32 * 8))[2:-1] pbkdf2 = hashlib.pbkdf2_hmac('sha512', password, salt, 25000, 512) key = hashlib.new('sha256', pbkdf2).hexdigest() IV = salt[:16] self.export_keyring(password, salt, user_pass) self.password = password self.salt = salt
def get_encryption_key(self, user_pass): # user_pass = raw_input("Enter your keyring password: ") password = hex(random.getrandbits(512 * 8))[2:-1] salt = hex(random.getrandbits(32 * 8))[2:-1] pbkdf2 = hashlib.pbkdf2_hmac('sha512', password, salt, 25000, 512) key = hashlib.new('sha256', pbkdf2).hexdigest() IV = salt[:16] # self.export_keyring(password, salt, user_pass) self.password = password self.salt = salt return key
def main(password): master_password = subprocess.check_output([ '/usr/bin/security', 'find-generic-password', '-w', '-s', 'Chrome Safe Storage', '-a', 'Chrome']).strip() key = hashlib.pbkdf2_hmac(hash_name='sha1', password=master_password, salt=b'saltysalt', iterations=1003, dklen=16) cipher = AES.new(key, AES.MODE_CBC, IV=b' ' * 16) return sys.stdout.write(cipher.decrypt(password.decode('base64')))
def _passwordToKey(cls, password, salt, rounds, alg): cls.logger.debug("_passwordToKey(%r, %r, %r, %r)", password, salt, rounds, alg) import hashlib, sys if sys.version_info >= (2, 7): return hashlib.pbkdf2_hmac(alg, password, salt, rounds) else: import backports.pbkdf2 return backports.pbkdf2.pbkdf2_hmac(alg, password, salt, rounds)
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()
def pbkdf2_hex(data, salt, iterations=1000, keylen=24, hashfunc=None): hashfunc = hashfunc or sha1 return hashlib.pbkdf2_hmac(hashfunc().name, data, salt, iterations, keylen).encode("hex")
def hash(): password = raw_input('Enter a password: ') dk = hashlib.pbkdf2_hmac('sha256', password, salt, 112000) hex = binascii.hexlify(dk) print(hex)
def password_check(update, password): user_id = update.message.from_user.id dk = '0000' try: dk = hashlib.pbkdf2_hmac('sha256', password, salt, 112000) except UnicodeEncodeError as e: text_reply(update, lang(user_id, 'encoding_error')) sleep(0.5) hex = binascii.hexlify(dk) return hex
def password_callback(bot, update, args): user_id = update.message.from_user.id chat_id = update.message.chat_id if (len(args) > 0): check = mysql_check_password(user_id) if (check is False): if (len(args[0]) >= 8): password = args[0] if ((len(set(string.digits).intersection(password)) > 0) and (len(set(string.ascii_uppercase).intersection(password))> 0) and (len(set(string.ascii_lowercase).intersection(password)) > 0)): try: dk = hashlib.pbkdf2_hmac('sha256', password, salt, 112000) hex = binascii.hexlify(dk) mysql_set_password(user_id, hex) message_markdown(bot, chat_id, lang(user_id, 'password_success')) logging.info('Password added for user {0}'.format(user_id)) except UnicodeEncodeError: text_reply(update, lang(user_id, 'password_uppercase')) logging.info('Password set failed for user {0}. Reason: Unicode symbol'.format(user_id)) else: text_reply(update, lang(user_id, 'password_uppercase')) logging.info('Password set failed for user {0}. Reason: uppercase-lowercase-digits'.format(user_id)) else: text_reply(update, lang(user_id, 'password_short')) logging.info('Password set failed for user {0}. Reason: Too short'.format(user_id)) else: text_reply(update, lang(user_id, 'password_not_empty')) logging.info('Password set failed for user {0}. Reason: Already protected'.format(user_id)) else: text_reply(update, lang(user_id, 'password_command'))
def passwordHashing(self, username, password): mode = 'utf-8' # uses the username as salt usernameSalt = str(username) # adds to the username to make a more secure salt salt = usernameSalt + 'This is CSC 376' finalSalt = str.encode(salt) self.salt = finalSalt iterations = 22000 password = str.encode(password) # TODO: Change this to use Argon2 (see argon2 0.1.10 BETA) instead. Far more resistant to GPU and ASIC based attacks. hex = hashlib.pbkdf2_hmac(hash_name='sha256', password=password, salt=finalSalt, iterations=iterations, dklen=128) hashHex = str(binascii.hexlify(hex)) return hashHex #a = LoginEncoding() #a.setUsername("jessicahua95") #a.setPassword("hello") #print("Username: " + a.getUsername()) #print(a.loginDecryption(a.getUsername())) #print(a.getPasswordSalt()) #print("Password: " + a.getPassword()) #print(a.checkPassword())
def __init__(self, _class, *, port, secret=None): if secret is None: secret = 'secret' self._class = _class self._port = int(port) self._secret = binascii.hexlify( hashlib.pbkdf2_hmac('sha256', secret.encode('utf-8'), str(port).encode('utf-8'), 100000) ) self._instance = None self._new_instance = False
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))
def compute_hash(password, salt): return hashlib.pbkdf2_hmac('sha256', password.encode('utf-8'), salt, 5000)
def salted_password(salt, iterations, algorithm_name, password): dk = pbkdf2_hmac(algorithm_name, password.encode(), urlsafe_b64decode(salt), int(iterations)) encrypt_password = hexlify(dk) return encrypt_password
def salted_password_2(salt, iterations, algorithm_name, password): dk = pbkdf2_hmac(algorithm_name, password.encode(), unhexlify(salt), int(iterations)) encrypt_password = hexlify(dk) return encrypt_password
def gen_derived_key(pre_shared_key, message_salt): enc_derived_key = hashlib.pbkdf2_hmac('sha256', pre_shared_key, message_salt, 5000000) return enc_derived_key
def encrypt_key(key, password): """Encrypt the given key through the provided password. :param bytes key: The 16 bytes key for the volume. :param bytes password: The password (in bytes form) provided by the user. """ salt = os.urandom(16) key_opener = hashlib.pbkdf2_hmac('sha256', password, salt, 100000, dklen=16) key_encrypted = bytes(a ^ b for a, b in zip(key, key_opener)) return salt, key_encrypted
def hash_password(password): """Convert a password to being hashed.""" dk = hashlib.pbkdf2_hmac( PASSWORD_ALGORITHM, password.encode("utf-8"), PASSWORD_SALT.encode("utf-8"), PASSWORD_ROUNDS) return binascii.hexlify(dk).decode("utf-8")
def chrome_process(safe_storage_key, chrome_data): # Salt, iterations, iv, size -> https://cs.chromium.org/chromium/src/components/os_crypt/os_crypt_mac.mm iv = "".join(("20",) * 16) key = pbkdf2_hmac("sha1", safe_storage_key, b"saltysalt", 1003)[:16] copy_path = tempfile.mkdtemp() # Work around for locking DB with open(chrome_data, "r") as content: dbcopy = content.read() with open("{0}/chrome".format(copy_path), "w") as content: # If Chrome is open the DB will be locked, get around this by making a temp copy. content.write(dbcopy) database = sqlite3.connect("{0}/chrome".format(copy_path)) if "Web Data" in chrome_data: sql_query = "select name_on_card, card_number_encrypted, expiration_month, expiration_year from credit_cards" else: sql_query = "select username_value, password_value, origin_url, submit_element from logins" decrypted_list = [] with database: for values in database.execute(sql_query): if values[0] == '' or (values[1][:3] != b"v10"): # User will be empty if they have selected "never" store password. continue else: decrypted_list.append((str(values[2]).encode("ascii", "ignore"), values[0].encode("ascii", "ignore"), str(chrome_decrypt(values[1], iv, key)).encode("ascii", "ignore"), values[3])) shutil.rmtree(copy_path) return decrypted_list
def register(self, username, password, code): #Query met parameters sqlQuery = "Select * from tbl_users WHERE username = '{param1}'" sqlCommand = sqlQuery.format(param1=username) self.__cursor.execute(sqlCommand) result = self.__cursor.fetchone() if int(code) == 25081998: if result: message = "Error: Deze gebruiker bestaat al" else: pwd_bytes = password salt_bytes = os.urandom(16) hash_bytes = hashlib.pbkdf2_hmac('sha256', pwd_bytes, salt_bytes, 100000) salt_string = binascii.hexlify(salt_bytes).decode('utf-8') hash_string = binascii.hexlify(hash_bytes).decode('utf-8') sqlQuery2 = "INSERT INTO tbl_users (username, pwd_hash, pwd_salt) VALUES ('{param1}', '{param2}', '{param3}')" sqlCommand2 = sqlQuery2.format(param1=username, param2=hash_string, param3=salt_string) self.__cursor.execute(sqlCommand2) self.__connection.commit() self.__cursor.close() message = "Succesvol geregistreerd" else: message = "Error: Foute code" return message