Encrypt and Decrypt Files using Python - GeeksforGeeks (2024)

Encryption is the act of encoding a message so that only the intended users can see it. We encrypt data because we don’t want anyone to see or access it.

We will use the cryptography library to encrypt a file. The cryptography library uses a symmetric algorithm to encrypt the file. In the symmetric algorithm, we use the same key to encrypt and decrypt the file. The fernet module of the cryptography package has inbuilt functions for the generation of the key, encryption of plain text into cipher text, and decryption of cipher text into plain text using the encrypt() and decrypt() methods respectively. The fernet module guarantees that data encrypted using it cannot be further manipulated or read without the key.

We are going to use the nba.csv file to perform all operations.

Installation:

The cryptography library can be installed using the below command:

pip install cryptography

Generate Key to encrypt the file

In the cryptography library, there is a cryptography algorithm called fernet. We will use the fernet module to encrypt the file.

Python3

# import required module

from cryptography.fernet import Fernet

Generating the key and saving it:

Python3

# key generation

key = Fernet.generate_key()

# string the key in a file

with open('filekey.key', 'wb') as filekey:

filekey.write(key)

Above code will generate a file with the name filekey.key. The file will contain one line, which is a string acting as a key i.e. J64ZHFpCWFlS9zT7y5zxuQN1Gb09y7cucne_EhuWyDM=

Encrypt the file using the key generated

Now we have an encrypted key and file to be encrypted. Now write code to encrypt this file:

  1. Open the file that contains the key.
  2. Initialize the Fernet object and store it in the fernet variable.
  3. Read the original file.
  4. Encrypt the file and store it into an object.
  5. Then write the encrypted data into the same file nba.csv.

Python3

# opening the key

with open('filekey.key', 'rb') as filekey:

key = filekey.read()

# using the generated key

fernet = Fernet(key)

# opening the original file to encrypt

with open('nba.csv', 'rb') as file:

original = file.read()

# encrypting the file

encrypted = fernet.encrypt(original)

# opening the file in write mode and

# writing the encrypted data

with open('nba.csv', 'wb') as encrypted_file:

encrypted_file.write(encrypted)

The nba.csv file before executing the above program:

Encrypt and Decrypt Files using Python - GeeksforGeeks (1)

The nba.csv file after executing the above program:

Encrypt and Decrypt Files using Python - GeeksforGeeks (2)

Decrypt the encrypted file

We have to use the same key to decrypt the file:

  1. Initialize the Fernet object and store it in the fernet variable.
  2. Read the encrypted file.
  3. Decrypt the file and store it into an object.
  4. Then write the decrypted data into the same file nba.csv.

Python3

# using the key

fernet = Fernet(key)

# opening the encrypted file

with open('nba.csv', 'rb') as enc_file:

encrypted = enc_file.read()

# decrypting the file

decrypted = fernet.decrypt(encrypted)

# opening the file in write mode and

# writing the decrypted data

with open('nba.csv', 'wb') as dec_file:

dec_file.write(decrypted)

The nba.csv file before executing the above program:

Encrypt and Decrypt Files using Python - GeeksforGeeks (3)

The nba.csv file after executing the above program:

Encrypt and Decrypt Files using Python - GeeksforGeeks (4)


My Personal Notesarrow_drop_up

Encrypt and Decrypt Files using Python - GeeksforGeeks (2024)

FAQs

How do you encrypt and decrypt data in Python? ›

To encrypt and decrypt a Python string, install and import the cryptography library, generate a Fernet key, and create a Fernet object with it. You can then encrypt the string using the Fernet. encrypt() method and decrypt the encrypted string using the Fernet. decrypt() method.

How do you encrypt and decrypt a text file in Python? ›

Let's discuss what we did here:
  1. We initialize the Fernet object as store is as a local variable f.
  2. Next, we read our original data (grades. csv file) into original.
  3. Then we encrypt the data using the Fernet object and store it as encrypted.
  4. And finally, we write it into a new . csv file called “enc_grades. csv”

Which algorithm is best for encryption and decryption in Python? ›

Cryptography with Python - Caesar Cipher
  • Caesar Cipher Technique is the simple and easy method of encryption technique.
  • It is simple type of substitution cipher.
  • Each letter of plain text is replaced by a letter with some fixed number of positions down with alphabet.

How to encrypt text file with password in Python? ›

It's set to work with bytes data, so if you want to encrypt strings or use string passwords make sure you encode() them with a proper codec before passing them to the methods. If you leave the encode parameter to True the encrypt() output will be base64 encoded string, and decrypt() source should be also base64 string.

How to encrypt and decrypt using public and private key in Python? ›

We will implement this using the code below:
  1. def generateKeys(): (publicKey, privateKey) = rsa. ...
  2. def loadKeys(): with open('keys/publicKey.pem', 'rb') as p: publicKey = rsa. ...
  3. def encrypt(message, key): return rsa. ...
  4. def decrypt(ciphertext, key): try: return rsa. ...
  5. def sign(message, key): return rsa.
Jan 28, 2022

Can Python encrypt files? ›

In Python, it is possible to encrypt and decrypt files before transmitting to a communication channel. For this, you will have to use the plugin PyCrypto. You can installation this plugin using the command given below.

How do I encrypt and decrypt a file? ›

Right-click (or press and hold) a file or folder and select Properties. Select the Advanced button and select the Encrypt contents to secure data check box. Select OK to close the Advanced Attributes window, select Apply, and then select OK.

How to encrypt and decrypt using AES Python? ›

And that is all there is to encrypting and decrypting a file using AES in python. We need to generate or obtain a key, create the initialization vector and write the original file size followed by the IV into the output file. This is followed by the encrypted data. Finally decryption does the same process in reverse.

What command can be used to encrypt and decrypt a file? ›

A command line utility, CIPHER. EXE, can be used to encrypt and decrypt files from the command line. /E Encrypts the specified directories.

Which method is used to encrypt to decrypt messages? ›

The science of encrypting and decrypting information is called cryptography. In computing, unencrypted data is also known as plaintext, and encrypted data is called ciphertext. The formulas used to encode and decode messages are called encryption algorithms, or ciphers.

What is the best file encryption in Python? ›

PyCrypto seems to be the best one around. It's comprehensive and the original author AMK is a respected Python developer.

What are the different types of encryption in Python? ›

There are three primary types of cryptography: Symmetric key cryptography. Asymmetric key cryptography.

What is the strongest data encryption algorithm? ›

AES 256-bit encryption is the strongest and most robust encryption standard that is commercially available today.

How do you make an encryption algorithm in Python? ›

Algorithm for Cryptography with Python
  1. Make a list of all the alphabet.
  2. Create a function that takes the text and a number as a parameter.
  3. Move through each element.
  4. If it's a space add it to the new list as it is.
  5. Take out the position of the character it should replace with.
  6. Join.
  7. Display the encrypted text.

How do I encrypt a large file in Python? ›

  1. Read n bytes of data ( raw_chunk )
  2. Encrypt n bytes with Fernet to create an m bytes chunk ( enc_chunk ).
  3. Use len(enc_chunk). to_bytes(4, "big") to write the size of the encrypted chunk to the file.
  4. Write the encrypted chunk to the file.
  5. Break when I read a b""
Sep 24, 2021

How to encrypt docx file in Python? ›

The following are the steps to password-protect a Word DOCX file in Python.
  1. First, load the Word document using Document class.
  2. Create an object of OoxmlSaveOptions class (to save in DOC format, use DocSaveOptions class instead).
  3. Set password using OoxmlSaveOptions.
Nov 15, 2021

What is the best way to encrypt private keys? ›

The most secure method of storing your private keys is to use some form of cryptographic hardware storage device. While they can be expensive, tools like Hardware Storage Modules (HSM), Smart Cards, or USB tokens are great lines of defense against an attack.

How do you decrypt a message in Python? ›

To decrypt the message, we just call the decrypt() method from the Fernet library. Remember, we also need to load the key as well, because the key is needed to decrypt the message.

How to encrypt and decrypt a message using RSA algorithm Python? ›

RSA Algorithm: Theory and Implementation in Python
  1. Also read: A* Algorithm – Introduction to The Algorithm (With Python Implementation)
  2. Example: Let p=3 and q=11 (both are prime numbers).
  3. Encryption: C = (M^e) mod n = 31^7 mod 33 = 4.
  4. Decryption: M = (C^d) mod n = 4^3 mod 33 = 31.
  5. Output:
Feb 27, 2023

How to decrypt and encrypt password Python? ›

How to encrypt and decrypt data in Python
  1. from cryptography. fernet import Fernet.
  2. key = Fernet. generate_key() f = Fernet(key)
  3. print(encrypted_data)
  4. print(decrypted_data. decode())
  5. from cryptography. fernet import Fernet key = Fernet. generate_key() print("Key : ", key. decode()) f = Fernet(key) encrypted_data = f.
Feb 11, 2021

How do I secure a file in Python? ›

Here are the Python security tips we'll explore:
  1. Always sanitize external data.
  2. Scan your code.
  3. Be careful when downloading packages.
  4. Review your dependency licenses.
  5. Do not use the system standard version of Python.
  6. Use Python's capability for virtual environments.
  7. Set DEBUG = False in production.
Sep 27, 2021

Can hackers access encrypted files? ›

Can hackers see encrypted data? No, hackers cannot see encrypted data, as it is scrambled and unreadable until the encryption key (or passphrase) is used to decrypt it. However, if a hacker manages to obtain the encryption key or crack the encryption algorithm, then they can gain access to the data.

What is the easiest way to encrypt a file? ›

How to encrypt a file folder or file
  1. On your home computer, choose the file or folder you want to encrypt and right-click on it.
  2. Select Properties.
  3. Select the Advanced button then check the box next to Encrypt contents to secure data.
  4. Press OK, which will close the Advanced Attributes window.
Aug 5, 2019

How to decrypt a file without certificate? ›

You can follow the steps below to decrypt a file on Windows 10:
  1. Select "Programs or All Programs" under the start menu, click "Accessories", and then choose "Windows Explorer".
  2. Right-click the file you want to decrypt, and click "Properties".
  3. Click "Advanced".
  4. Clear the Encrypt contents and then click "OK".
Feb 22, 2023

How to decrypt a file with a private key? ›

How to Decrypt an RSA Private Key Using OpenSSL
  1. Open terminal.
  2. Run the open ssl command to decrypt the file $ openssl rsa -in <encrypted_private.key> -out <decrypted_private.key> Enter pass phrase for encrypted_private.key: <enter the password> writing RSA key.
Feb 22, 2021

How to install AES encryption in Python? ›

To install it:
  1. Using setuptools: python setup.py install.
  2. Using pip: pip install aes_cipher.

What is an example of a 64 bit encryption key? ›

But, in any case, 64 bits (16 hexadecimal digits) is the round number upon which DES is organized. For example, if we take the plaintext message "8787878787878787", and encrypt it with the DES key "0E329232EA6D0D73", we end up with the ciphertext "0000000000000000".

How to encrypt and decrypt file using AES algorithm? ›

enc : This command is used for encryption of audio information time openssl aes-256-cbc –a -d –iter 1024 –in encrypt. enc –out decrypt. decry : This command is used for decryption of audio information. The original text file is encrypted and decrypted using the command and also time for execution is also calculated.

What are the methods for encrypting files? ›

There are two types of encryption in widespread use today: symmetric and asymmetric encryption. The name derives from whether or not the same key is used for encryption and decryption.

How do hackers encrypt files? ›

Typically, the software gets introduced to your network by an executable file that may have been in a zip folder, embedded within Microsoft Office document's macros, or disguised as fax or other viable attachment. The download file then encrypts your data, adds an extension to your files and makes them inaccessible.

What are encryption and decryption methods? ›

Encryption is the process by which a readable message is converted to an unreadable form to prevent unauthorized parties from reading it. Decryption is the process of converting an encrypted message back to its original (readable) format. The original message is called the plaintext message.

What are the three 3 different encryption methods? ›

DES, AES, and RSA are the three primary encryption types. A more recent 3DES is a block cipher that is still in use today. The Triple Data Encryption Standard (3DES) does exactly what its name says. For triple protection, it employs three independent 56-bit keys rather than a single 56-bit key.

What are the four 4 most secure encryption techniques? ›

Here are some of the top encryption methods that you can use to safeguard sensitive data for your small business.
  1. Advanced Encryption Standard (AES) ...
  2. Rivest-Shamir-Adleman (RSA) ...
  3. Triple Data Encryption Standard (DES) ...
  4. Blowfish. ...
  5. Twofish. ...
  6. Format-Preserving Encryption (FPE) ...
  7. Elliptic Curve Cryptography (ECC)
Oct 6, 2022

What are the 3 methods of encrypting text? ›

The three major encryption types are DES, AES, and RSA.

How do you check if a file is encrypted or not in Python? ›

The most often used solution is to write some "magic" string at the beginning of the encrypted file followed by the encrypted content. If that string is found when reading the file, further encryption is refused. For decription it is read to veryfiy that this is a file we encrypted, but otherwise it is ignored.

What is the fastest encryption method? ›

Advanced Encryption Standard (AES) Algorithm

The Advanced Encryption Standard is the most common and extensively used symmetric encryption algorithm that is likely to be encountered nowadays (AES). It has been discovered to be at least six times quicker than triple DES.

How Python is more secure? ›

Python is extremely useful in cybersecurity as it performs many functions, such as scanning and malware analysis. So, keeping all the above perks of Python in mind, you can hire a python developer in India to secure your web application.

What are the two types of encryption allowed in always encrypted? ›

Always Encrypted uses two types of keys: Column master keys and column encryption keys.

What are the two 2 major types of encryption methods that are used with at least one example in each? ›

The two main kinds of encryption are symmetric encryption and asymmetric encryption. Asymmetric encryption is also known as public key encryption. In symmetric encryption, there is only one key, and all communicating parties use the same (secret) key for both encryption and decryption.

How to encode a password in Python? ›

Encrypting a Password in Python With bcrypt:
  1. #Sample python code that depicts the usage of bcrypt function for hashing of the specified input text.
  2. # Importing the required libraries that will be used across the code.
  3. import bcrypt.
  4. import sys.

What is the weakest encryption method? ›

Encryption algorithms such as TripleDES and hashing algorithms such as SHA1 and RIPEMD160 are considered to be weak. These cryptographic algorithms do not provide as much security assurance as more modern counterparts.

What is the weakest form of encryption? ›

WEP is the weakest WiFi encryption standard.

Which encryption method is most widely used and why? ›

AES and 3DES are the most widely used encryption method as it is strong and cannot be broken easily. The encryption of each data block happens with random salt making it complex and adding another layer of security to it.

How to install cryptography in Python? ›

Type "cmd" in the search bar and hit Enter to open the command line. What is this? Type “ pip install cryptography ” (without quotes) in the command line and hit Enter again. This installs cryptography for your default Python installation.

What is the simple algorithm for encryption method? ›

One very basic symmetric encryption algorithm is known as the rotational cipher. In this algorithm, the sender simply "adds" the key to each character of the cleartext message to form the ciphertext. For example, if the key is 2, "A" would become "C", "B" would become "D", and so on.

What is the largest file Python can open? ›

There is no reachable maximum on the size of a file Python can open. People regularly load gigabytes of data into memory. Depending on your computer's RAM and whether it's 64- or 32- bit OS/processor, the practical maximum for you may be anywhere from 1 GB up before you get a MemoryError.

Is there a limit to how much you can write to a file Python? ›

There is no limit to the number of characters you can read and write to files in Python.

How do you handle large data files in Python? ›

Reading Large Text Files in Python

We can use the file object as an iterator. The iterator will return each line one by one, which can be processed. This will not read the whole file into memory and it's suitable to read large files in Python.

How do I encrypt a PDF in Python? ›

The code block above does the following:
  1. Import the PdfReader and PdfWriter functions from the module PyPDF2.
  2. The reader variable reads the PDF and initializes it as an object.
  3. The PdfWriter() class supports writing the PDF files out that will later make sure the file is saved.
Sep 5, 2022

Can private keys be decrypted? ›

Private key encryption systems use a single key that is shared between the sender and the receiver. Both must have the key; the sender encrypts the message by using the key, and the receiver decrypts the message with the same key.

Which is better public or private key encryption? ›

Conclusion. To conclude, private keys can be used for both encryption and decryption, while Public keys are used only for the purpose of encrypting the sensitive data. Private keys are shared between the sender and the receiver, whereas public keys can be freely circulated among multiple users.

Which is the most secure public key? ›

RSA vs. DSA vs. ECDSA vs. EdDSA
RSAEdDSA
SecuritySpecialized algorithms like Quadratic Sieve and General Number Field Sieve exist to factor integers with specific qualities.EdDSA provides the highest security level compared to key length. It also improves on the insecurities found in ECDSA.
2 more rows
Apr 7, 2022

How to decrypt data using Python? ›

Decrypting a File
  1. We initialize the Fernet object as store is as a local variable f.
  2. Next, we read our encrypted data (enc_grades. csv file) into encrypted.
  3. Then we decrypt the data using the Fernet object and store it as decrypted.
  4. And finally, we write it into a new . csv file called “dec_grades. csv”

How does encryption work in Python? ›

Explanation. Plain text is stored in the variable message and the translated variable is used to store the cipher text created. The length of plain text is calculated using for loop and with help of index number. The characters are stored in cipher text variable translated which is printed in the last line.

How do I encrypt and decrypt messages? ›

Encrypt & Decrypt Text Online
  1. Enter any text to be Encrypted.
  2. Encrypt with a custom secret key.
  3. Enter Secret Key(Remember, the encrypted text can't be decrypted without this secret key)
  4. Encrypted Output:

What is the secret key used to encrypt and decrypt messages? ›

The private key is used to decrypt, as well as to encrypt, so using it for symmetric encryption requires a key exchange to share that key securely with trusted parties authorized to exchange secured data. Cryptographic software is usually used to automate this process. Key management.

What are the main methods to encrypt and decrypt information? ›

The two main kinds of encryption are symmetric encryption and asymmetric encryption. Asymmetric encryption is also known as public key encryption. In symmetric encryption, there is only one key, and all communicating parties use the same (secret) key for both encryption and decryption.

How to encrypt in Python and decrypt in Java? ›

The requirement was to be able to encrypt text in Python and decrypt it in Java, and vice versa.
...
run.sh
  1. encrypt | decrypt , to tell the program whether to encrypt or decrypt the message.
  2. key , which must be 16 bytes long, e.g. "ThisIsA16ByteKey"
  3. message , the plaintext or encrypted message to be encrypted or unencrypted.

How to secure data in Python? ›

Here are the top 10 Python security programming practices, developers should practice ensuring the least vulnerability.
  1. Update the Python version frequently. ...
  2. Be cautious while sharing. ...
  3. Ensure the inputs are sanitized. ...
  4. Use prepared statements. ...
  5. Go virtual for Python programming. ...
  6. Do not share your secrets.
Jul 12, 2022

What is an algorithm used to encrypt and decrypt text? ›

The correct answer is Cipher. Cipher is an algorithm for performing encryption or decryption—a series of well-defined steps that can be followed as a procedure. A cipher suite uses one algorithm for encryption, another algorithm for message authentication, and another for key exchange.

What are three 3 methods for encrypting data? ›

The three major encryption types are DES, AES, and RSA. While there are many kinds of encryption - more than can easily be explained here - we will take a look at these three significant types of encryption that consumers use every day.

What are the two 2 methods of encryption? ›

There are two types of encryption in widespread use today: symmetric and asymmetric encryption.

How do I encrypt a binary file in Python? ›

Encrypt a file

We first read any file as binary file (hence use the 'rb' mode). Then we convert the read in data into an array of bytes. We then apply the XOR operation on each element of the array using a given key. The XOR operation (or “exclusive or” in Python) compares two binary numbers bitwise.

How do you encrypt and decrypt using public and private key? ›

Public key encryption

One key is nominated as the private key and is kept secret. The other key is distributed to anyone who wants it; this key is the public key. Anyone can encrypt a message by using your public key, but only you can read it. When you receive the message, you decrypt it by using your private key.

What is the sample code for encryption and decryption in Java? ›

Encryption and decryption example

encrypt(originalString, secretKey) ; String decryptedString = AES. decrypt(encryptedString, secretKey) ; System. out. println(originalString); System.

Why Python is good for security? ›

Python programming allows cyber pros to write scripts, automate processes and customize tools to support a number of offensive and defensive cybersecurity functions including: Malware analysis. Wireless network scanning. Port scanning.

Why is Python most secure? ›

The security of Python code

Python has a dynamic type system, which makes it easy to crash a program (or at least, raise exceptions).

Top Articles
Latest Posts
Article information

Author: Jonah Leffler

Last Updated:

Views: 6460

Rating: 4.4 / 5 (65 voted)

Reviews: 80% of readers found this page helpful

Author information

Name: Jonah Leffler

Birthday: 1997-10-27

Address: 8987 Kieth Ports, Luettgenland, CT 54657-9808

Phone: +2611128251586

Job: Mining Supervisor

Hobby: Worldbuilding, Electronics, Amateur radio, Skiing, Cycling, Jogging, Taxidermy

Introduction: My name is Jonah Leffler, I am a determined, faithful, outstanding, inexpensive, cheerful, determined, smiling person who loves writing and wants to share my knowledge and understanding with you.