Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

python
communitycreator

How to encrypt and decrypt text data in Python

Harsh Jain

Introduction

In this shot, we are going to discuss how to encode and decode text data in Python.

While sending data from your network to resources that are placed outside of your network, you might worry that the data is visible to outsiders during the transfer. One of the solutions is to encode your data before sending it to any resource that is outside your network. To encode your data means to make it so that even if someone can view your data, they will not be able to understand it. Let’s define encoding and decoding:

  • Encoding: the process of converting original text to random and meaningless text called ciphertext.
  • Decoding: the process of converting ciphertext back to the original text.

We will be using a Python package called base64 to perform encoding-decoding of text. Take a look at the code below:

import base64

data = b'data to be encoded'
encoded_data = base64.b64encode(data)
print(encoded_data)

decoded_data = base64.b64decode(encoded_data)
print(decoded_data)
Encrypt and decrypt text using Python

Explanation:

  • In line 1, we import the required package.
  • In line 3, we define the data that we want to encode.
  • In line 4, we use the b64encode() function to encode the data.
  • In line 5, we print the encoded_data.
  • In line 7, we use the b64decode() function to decode the encoded_data.
  • In line 8, we print the decoded data.

We can easily transform the original data to ciphertext and decode it on the receiver’s end with the above method.

RELATED TAGS

python
communitycreator
RELATED COURSES

View all Courses

Keep Exploring