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')
python类pbkdf2_hmac()的实例源码
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 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 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 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 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 _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 generateKey(self, key, salt):
# 2 Iterations of PBKDF2 SHA256
return hashlib.pbkdf2_hmac('sha256', key, salt, 2)
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