Daniel Contreras
Daniel Contreras

Reputation: 61

Encrypt and protect file with python

I want to create a file in a python3 program, in which I want to store some information that I don't want users to see or manipulate. However, in execution time I need to read and modify its content, being sure that users cannot modify the content of the file. How can I achive this?

Upvotes: 1

Views: 7887

Answers (2)

ChatoPaka
ChatoPaka

Reputation: 150

All information stored on end-user devices can eventually be manipulated.
One option is storing the data you don't want users to manipulate on a web-server and retrieve/update it when needed. The downside of this approach is that your code cannot work offline.

Upvotes: 2

Umb
Umb

Reputation: 34

In this example I used Fernet and a key created with a password "hardcode". You can encrypt the file and decrypt the information inside only when they are necessary. If you have to modify the information, you can just call again the encrypt function.

from cryptography.fernet import Fernet
import base64, hashlib


def encrypt(filename, key):
    f = Fernet(key)
    with open(filename, "rb") as file:
        # read the encrypted data
        file_data = file.read()
    # encrypt data
    encrypted_data = f.encrypt(file_data)
    # write the encrypted file
    with open(filename, "wb") as file:
        file.write(encrypted_data)
    
    
def decrypt(filename, key):
    f = Fernet(key)
    with open(filename, "rb") as file:
        # read the encrypted data
        encrypted_data = file.read()
    # decrypt data
    decrypted_data = f.decrypt(encrypted_data)
    print(decrypted_data)

my_password = 'mypassword'.encode()
key = hashlib.md5(my_password).hexdigest()
key_64 = base64.urlsafe_b64encode(key.encode("utf-8"))

# file name
file = "test.txt"
# encrypt it
encrypt(file, key_64)
with open("test.txt", "rb") as f:
    print(f.read())
decrypt(file, key_64)

Upvotes: 0

Related Questions