Skip to content

Instantly share code, notes, and snippets.

@yezz123
Created August 22, 2021 14:28
Show Gist options
  • Save yezz123/db24ac1cadc19b3e2a84702ff32d60ec to your computer and use it in GitHub Desktop.
Save yezz123/db24ac1cadc19b3e2a84702ff32d60ec to your computer and use it in GitHub Desktop.
A little Password Handler using Crypto Cipher and Hashlib and Bcrypt ๐Ÿ› 
import typing
import hashlib
from binascii import b2a_hex, a2b_hex
import bcrypt
from Crypto.Cipher import AES
class AesCrypto:
def __init__(self, key: str, key_length: int = 16):
self.key = key.zfill(key_length)
self.mode = AES.MODE_CBC
def encrypt(self, text: str) -> str:
text = text.encode("utf-8")
cryptor = AES.new(self.key.encode("utf8"), self.mode, self.key.encode("utf8"))
length = 16
count = len(text)
add = length - (count % length)
text = text + (b"\0" * add)
ciphertext = cryptor.encrypt(text)
return b2a_hex(ciphertext).decode("ASCII")
def decrypt(self, text) -> str:
cryptor = AES.new(self.key.encode("utf8"), self.mode, self.key.encode("utf8"))
plain_text = cryptor.decrypt(a2b_hex(text))
return plain_text.rstrip(b"\0").decode("utf8")
class NsPwdCrypto:
def __init__(self, aes_obj: AesCrypto):
self.aes_obj = aes_obj
@staticmethod
def sha_pwd(pwd: str) -> str:
sha_512 = hashlib.sha512()
sha_512.update(pwd.encode("utf8"))
sha_pwd = sha_512.hexdigest()
return sha_pwd
@staticmethod
def bcrypt_pwd(pwd: str, salt: typing.Optional[bytes] = None) -> str:
if salt is not None:
bcrypt_pwd = bcrypt.hashpw(pwd.encode("utf8"), salt=salt)
else:
bcrypt_pwd = bcrypt.hashpw(pwd.encode("utf8"), bcrypt.gensalt())
return bcrypt_pwd.decode("utf8")
def aes_pwd(self, pwd: str) -> str:
aes_pwd = self.aes_obj.encrypt(pwd)
return aes_pwd
def crypto_pwd(self, pwd: str) -> str:
sha_pwd = self.sha_pwd(pwd)
bcrypt_pwd = self.bcrypt_pwd(sha_pwd)
aes_pwd = self.aes_pwd(bcrypt_pwd)
return aes_pwd
def check_pwd(self, pwd: str, crypto_pwd: str) -> bool:
salt = self.aes_obj.decrypt(crypto_pwd).encode("utf8")
sha_pwd = self.sha_pwd(pwd)
bcrypt_pwd = self.bcrypt_pwd(sha_pwd, salt)
return bcrypt_pwd == salt
aes_handler = AesCrypto(key="4190dbe7b5f7db0b")
pwd_handler = NsPwdCrypto(aes_handler)
if __name__ == "__main__":
s = pwd_handler.crypto_pwd("123456")
print(s)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment