Search code examples
pythonpython-3.xpython-cryptography

Data Encryption static encrypt


My hexidigit is changing on day by day basis. How can I change it back to static

Code

from Crypto.Cipher import AES
import pandas as pd
import mysql.connector

myconn = mysql.connector.connect(host="######", user="##", password="######", database="#######")
query = """SELECT * from table """
df = pd.read_sql(query, myconn) #getting hexidigit back from the SQL server after dumping the ecrypted data into the database

def resize_length(string):
    #resizes the String to a size divisible by 16 (needed for this Cipher)
    return string.rjust((len(string) // 16 + 1) * 16)

def encrypt(url, cipher):
    # Converts the string to bytes and encodes them with your Cipher
    cipherstring = cipher.encrypt(resize_length(url).encode())
    cipherstring = "".join("{:02x}".format(c) for c in cipherstring)
    return cipherstring

def decrypt(text, cipher):
    # Converts the string to bytes and decodes them with your Cipher
    text = bytes.fromhex(text)
    original_url = cipher.decrypt(text).decode().lstrip()
    return original_url

# It is important to use 2 ciphers with the same information, else the system breaks
# Define the Cipher with your data (Encryption Key and IV)
cipher1 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
cipher2 = AES.new('This is a key123', AES.MODE_CBC, 'This is an IV456')
message = df['values'][4]
eypt = encrypt(message, cipher1)
print(decrypt(eypt, cipher2))

I'm able to decrypt the string after calling from database but on the next day the encrypted string changes which fails my code. How can I freeze this? Keeping a constant string everyday?


Solution

  • I got the solution by encrypting the key using bytes() Use the byte method to store the key in secured config file or database and encrypt the byte string to get the key. After that use any cipher method with suitable algorithm to encrypt the data and mask it.