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'))
python类pbkdf2_hmac()的实例源码
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 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 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 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 _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 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 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 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 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
def _hi(data, salt, iterations):
return pbkdf2_hmac('sha1', data, salt, iterations)