Skip to content

Instantly share code, notes, and snippets.

@sergiopena
Created October 14, 2025 14:07
Show Gist options
  • Select an option

  • Save sergiopena/b9ee6f45fb8ee76b93b60edc254d58e0 to your computer and use it in GitHub Desktop.

Select an option

Save sergiopena/b9ee6f45fb8ee76b93b60edc254d58e0 to your computer and use it in GitHub Desktop.
FMR encryption functions
import bcrypt
from Crypto.Cipher import AES
import string
import secrets
import uuid
import base64
import hashlib
def hash(text: str) -> str:
""" Hashes admin password ."""
salt = bcrypt.gensalt(rounds=10, prefix=b"2a")
return bcrypt.hashpw(text.encode('utf-8'), salt).decode()
def check(text: str, hash: str):
""" Checks if the plain text password matches the hashed password."""
return bcrypt.checkpw(text.encode('utf-8'), hash.encode('utf-8'))
def get_cipher(salt, password):
""" AES ECB cipher with PBKDF2 derivation key."""
key = hashlib.pbkdf2_hmac(hash_name='sha256',
password=password.encode('utf-8'),
salt=salt.encode('utf-8'),
iterations=1000,
dklen=32)
return AES.new(key, AES.MODE_ECB)
def pad(byte_array: bytearray):
""" PKCS5 padding."""
pad_len = 16 - len(byte_array) % 16
return byte_array + (bytes([pad_len]) * pad_len)
def unpad(byte_array: bytearray):
""" PKCS5 padding."""
return byte_array[:-ord(byte_array[-1:])]
def encrypt(text, salt, password):
""" Encrypt plain text using AES ECB cipher with PBKDF2 derivation key."""
text = pad(text.encode('UTF-8'))
cipher = get_cipher(salt, password)
return base64.b64encode(cipher.encrypt(text)).decode().replace('=','\\=')
def decrypt(text, salt, password):
""" Decrypt plain text using AES ECB cipher with PBKDF2 derivation key."""
cipher = get_cipher(salt, password)
msg_dec = cipher.decrypt(base64.b64decode(text))
return unpad(msg_dec).decode()
def generate_password() -> str:
""" Generates a random password."""
alphabet = string.ascii_letters + string.digits
return ''.join(secrets.choice(alphabet) for i in range(20)) # for a 20-character password
if __name__ == "__main__":
#
# Database credentials AES ECB with PBKDF2 derviation key
#
# database account plain password
database_plain_password = generate_password()
# encryption salt and password
salt = str(uuid.uuid4())
password = str(uuid.uuid4())
# database encrypted password
database_password_encrypted = encrypt(database_plain_password, salt=salt, password=password)
print(f"{'=' * 20} Database password encryption {'=' * 20}")
print(f'{salt=}')
print(f'{password=}')
print(f'{database_plain_password=}')
print(f'{database_password_encrypted=}')
#
# Admin password hashed using Blowfish
#
# plain admin password
admin_password = generate_password()
# hashed
admin_password_hash = hash(admin_password)
print(f"{'=' * 20} Admin password hashing {'=' * 20}")
print(f'{admin_password=}')
print(f'{admin_password_hash=}')
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment