Encrypt files with python

Шифрование и дешифрование файлов с помощью Python

Шифрование — это процесс кодирования информации, позволяющий только авторизованным сторонам получить к ней доступ.

Хотим поделиться с вами, как можно шифровать файлы, используя Python с помощью библиотеки cryptography, построенной на основе алгоритма AES. Возможно кому-то, также как и нам, такой способ покажется более простым для шифрования файла с данными.

В данном примере используется симметричное шифрование. Тот же ключ, который применяется для шифрования данных, можно использовать для их дешифрования.

Итак, установим библиотеку cryptography:

Открываем новый файл Python:

Создаем ключ и сохраняем его в файл, например, crypto.key:

def write_key(): # Создаем ключ и сохраняем его в файл key = Fernet.generate_key() with open(‘crypto.key’, ‘wb’) as key_file: key_file.write(key)

Внимание! Сгенерированный ключ crypto.key необходимо хранить в надежном месте. В случае его потери невозможно будет расшифровывать данные, которые были зашифрованы этим ключом.

Этот ключ уникален, и нет необходимости генерировать ключ каждый раз, когда потребуется зашифровать что-либо.

Создадим функцию для загрузки этого ключа:

def load_key(): # Загружаем ключ ‘crypto.key’ из текущего каталога return open(‘crypto.key’, ‘rb’).read()

Далее понадобится создать функцию для шифрования файла:

После инициализации объекта Fernet с заданным ключом прочитаем этот файл:

После этого, зашифровываем данные:

Запишем зашифрованный файл с тем же именем, чтобы он переопределил оригинал:

Теперь создадим функцию расшифровки файла:

def decrypt(filename, key): # Расшифруем файл и записываем его f = Fernet(key) with open(filename, ‘rb’) as file: # читать зашифрованные данные encrypted_data = file.read() # расшифровать данные decrypted_data = f.decrypt(encrypted_data) # записать оригинальный файл with open(filename, ‘wb’) as file: file.write(decrypted_data)

И, наконец, проверим это на конкретном файле, разместив шифруемый файл и ключ в текущем каталоге.

Например, для шифрования файла с именем ‘report.csv’вызываем созданную функцию encrypt():

# раскомментируйте следующую строку, если запускаете код впервые, чтобы сгенерировать ключ # write_key() # загрузить ключ key = load_key() # имя шифруемого файла file = ‘report.csv’ # зашифровать файл encrypt(file, key)

После шифрования будет видно, что размер файла ‘report.csv’увеличился, и мы не сможем прочитать содержимое этого файл.

Чтобы вернуть файл ‘report.csv’в исходную форму, вызовем функцию decrypt ():

Получаем исходный файл ‘report.csv’вместо ранее зашифрованного.

Обратите внимание на то, что при применении данного кода, размер файла не должен превышать объем оперативной памяти.

Применение этого несложного кода Python даст возможность надежно защитить данные от несанкционированного доступа к ним и соблюсти требования кибербезопасности при работе с критически важной информацией. При этом установки какого-либо специального программного обеспечения не требуется.

Источник

Шифрование и криптография в Python

В Python не так уж много инструментов стандартной библиотеки, которые работают с шифрованием. Однако, в нашем распоряжении есть библиотеки хешинга. Давайте рассмотрим этот вопрос в данной статье, но более детально сфокусируемся на двух сторонних пакетах: PyCrypto и cryptography. Мы научимся шифровать и расшифровывать строки при помощи двух этих библиотек.

Хеширование

Если вам нужно защитить хэши или алгоритм дайджеста сообщений, то для этого прекрасно подойдет модуль стандартной библиотеки Python hashlib. Он включает в себя безопасные алгоритмы хеширования FIPS, такие как SHA1, SHA224, SHA256, SHA384, а также SHA512 и MD5. Python также поддерживает функции хеширования adler32 и crc32, но они содержатся в модуле zlib. Одно из самых популярны применений хеширования это хранение хеша пароля, вместо самого пароля. Конечно, хеш должен быть хорошим, в противном случае он может быть расшифрован.

Другой популярный случай, в котором применяется хеширование – это хеширование файла, с последующей отправкой файла и его хеша по отдельности. Получатель файла может запустить хеш в файле, чтобы убедиться в том, что файл соответствует отправленному хешу. Если это так, значит никто не менял файл, когда он был отправлен. Давайте попробуем создать хеш md5. Но оказывается, чтобы использовать хеш md5, нужно передать его строке байта, вместо обычной. Так что мы попробовали сделать это, после чего вызвали метод дайджеста, чтобы получить наш хеш. Если вы претпочитаете хешированный дайджест, мы можем сделать и это:

Источник

How to Encrypt and Decrypt Files in Python?

How to Encrypt and Decrypt Files in Python?

In Encryption, we encode the data information that presents in plain text to an alternative ciphertext that is impossible to read and make sense of it. We generally use encryption to keep some data secret so that only authorized people can see the actual data.

Although there are various encryption algorithms out there, in this tutorial, we will be using Symmetric Encryption in which we require the same key to encrypt and decrypt the data.

The advantage of symmetric encryption is we only need to create one key that will be shared between the authorized people, and only those people can decrypt the encoded file.

In this Python tutorial, I will walk you through the Python program to encrypt and decrypt a text file using the cryptography library.

Install the Python cryptography Library

cryptography is an open-source Python library that contains many cryptographic algorithms to cipher the data. In this tutorial, we will be using this library for Symmetric ciphering and generating keys to encrypt and decrypt a text file.

To download the Python cryptography library, run the following pip install command on your terminal.

Encrypt a Text file in Python?

Let’s start with importing the Fernet module from the cryptography library.

from cryptography.fernet import Fernet

Now generate the key and save or write it locally using Python file handling.

#generate a key key = Fernet.generate_key() #save the key locally with open("my_key.key", "wb") as key_data: key_data.write(key)

The generate_key() function will generate random bytes keys. And using Python file handling, I wrote the key in binary format and saved it locally. We have saved the key locally because we require the same key to decrypt the encrypted file. Now let’s read the data.txt file which we are supposed to encrypt.

#get data.txt file with open("data.txt", "r") as file: data = file.read() print("The actual Data before Encryption:\n ", data)

Before we encrypt the data, let’s encode the string data with UTF-8 using the string encode() function. Because the encrypt function of the Fernet object requires byte encoded data.

#convert data into bytes byte_data = data.encode()

Now we need to initialize the Fernet object using the key we just generated.

#initialize Fernet object f= Fernet(key)

Now let’s encrypt the byte_data using the encrypt() function.

#encrypt bytes data encrypt_data = f.encrypt(byte_data)

The Fernet object f encrypt() function will encrypt the byte_data based on the key . Now write the encrypt_data to the existing data.txt file.

#write encoded data into data.txt with open("data.txt", "wb") as file: file.write(encrypt_data) print("The Encrypted data is\n: ", encrypt_data)

As you can see that I wrote them excrypt_data into the data.txt file with write binary mode. Now put the code together and execute.

Python Program to Encrypt File

from cryptography.fernet import Fernet #generate a key key = Fernet.generate_key() #save the key locally with open("my_key.key", "wb") as key_data: key_data.write(key) #get data.txt file with open("data.txt", "r") as file: data = file.read() print("The actual Data before Encryption:\n ", data) #convert data into bytes byte_data = data.encode() #initialize Fernet object f= Fernet(key) #encrypt bytes data encrypt_data = f.encrypt(byte_data) #write encoded data into data.txt with open("data.txt", "wb") as file: file.write(encrypt_data) print("\nThe Encrypted data is:\n ", encrypt_data)
The actual Data before Encryption: Step up and begin your game and if you are already in the journey, and enter the league of Tech Pros! Read tutorials, try examples, learn to code. Do whatever it takes to lead the tech world in this era! The Encrypted data is: b'gAAAAABgJmwywqYFtqW-pXUe9pwIx0KnZjLYkuPXEf2nb7SZzan_aTOtxMmXpw2viA96lgsztjzu3_LqKdWNwbOmIZNZWmpc4g1u3P0eeC-eMxiqSZGHFBEbR3Ekty8ccgNcVQXz1aw6cP1QodkoSU2fBbyfUTUekBWuSaCh53adGqJ28doyfTR5O-C9-IGU08I-PlYYd0nWBnqvrSMWJGlgoOnH2qMjUjMmn6wdy1aGAww_iT39bA3aPBzP93hBxGzZ9XIL-Qgfl5gReAQ7ts2UikShppwbvDCGmA3LRx2RwP0EKgk3n1PukkTzvefdEjmWXtAiJJ5vsEJ4B8AFKOqoigKKbcK9cw=='

From the output, you can see that the Actual data has been encrypted. Now, if you will check your Python script directory there, you will see a new file my_key.key that contains the key data for the encrypted file. In the next program, I will use the my_key.key key to decrypt the encrypted file.

Decrypt a Text file in Python?

Now let’s decrypt the data.txt file using the key that we created and saved in the above file. Let’s begin with importing the Fernet module from the cryptography library.

from cryptography.fernet import Fernet

Now let’s load the encrypted data.txt and my_key.key data, and print the Encrypted data.

#load the key with open("my_key.key" ,"rb") as my_key: key = my_key.read() #load encrypted file with open("data.txt", "rb") as file: encryp_data = file.read() print("The Encrypted Data is:\n", encryp_data)

Now initialize the Fernet object with the loaded key .

#initialize Fernet object with key f = Fernet(key)

Now decrypt the encrypted data using the Fernet object decrypt() function.

#decrypt data decrypt_data = f.decrypt(encryp_data) print("\nThe Actual Data is:\n", decrypt_data.decode())

The decode() is the string function that decodes the encoded UTF-8 string. Now, put all the code together and execute

Python Program to decrypt a file

from cryptography.fernet import Fernet #load the key with open("my_key.key" ,"rb") as my_key: key = my_key.read() #load encrypted file with open("data.txt", "rb") as file: encryp_data = file.read() print("The Encrypted Data is:\n", encryp_data) #initialize Fernet object with key f = Fernet(key) #decrypt data decrypt_data = f.decrypt(encryp_data) print("\nThe Actual Data is:\n", decrypt_data.decode())
The Encrypted Data is: b'gAAAAABgJmwywqYFtqW-pXUe9pwIx0KnZjLYkuPXEf2nb7SZzan_aTOtxMmXpw2viA96lgsztjzu3_LqKdWNwbOmIZNZWmpc4g1u3P0eeC-eMxiqSZGHFBEbR3Ekty8ccgNcVQXz1aw6cP1QodkoSU2fBbyfUTUekBWuSaCh53adGqJ28doyfTR5O-C9-IGU08I-PlYYd0nWBnqvrSMWJGlgoOnH2qMjUjMmn6wdy1aGAww_iT39bA3aPBzP93hBxGzZ9XIL-Qgfl5gReAQ7ts2UikShppwbvDCGmA3LRx2RwP0EKgk3n1PukkTzvefdEjmWXtAiJJ5vsEJ4B8AFKOqoigKKbcK9cw==' The Actual Data is: Step up and begin your game and if you are already in the journey, and enter the league of Tech Pros!

Conclusion

In this Python tutorial, we learned «How to Encrypt and Decrypt files in Python?». You can also encrypt and decrypt a file based on a simple and logical algorithm. But with the help of the Python cryptography library, you do not need to implement an algorithm of your own. You can simply use its generate_key(), encrypt, and decrypt function for file ciphering.

People are also reading:

Источник

Python File Encryption

Python File Encryption

In this Python article we want to learn about Python File Encryption, one of the best usage of Python programming language is in file encryption. so first of all let’s talk about encryption, so encryption is the process of encoding a message or information, after encryption only authorized parties can access it. in this article we want to talk about Python file encryption and how it can be implemented.

Why Encrypt Files ?

Let’s talk that why we need to encrypt a file, so as you know that data breaches and hacks are becoming more common, and if we have sensitive information then that is at risk. encryption is a way of protecting data from unauthorized users, by encrypting we make the data unreadable to unauthorized parties. we can say that encrypting files is particularly important when the information contained in the file is sensitive, such as financial information or personal data.

Now let’s talk about Python File Encryption, Python provides several libraries for file encryption, including cryptography library and hashlib library.

Python Cryptography Library

The cryptography library provides functions for implementing symmetric and asymmetric encryption.

This is an example of using symmetric encryption, in this example we are using Fernet class from the cryptography library to generate a key and encrypt a file. we open the file in binary mode, read the file into memory and encrypted that with Fernet cipher, and then write the information to a new file.

Источник

Читайте также:  Welcome to My Website!
Оцените статью