Introduction to Cryptography in Python

Cryptography: Cryptography is associated with the process of converting ordinary plain text into unintelligible text and vice-versa. It is a method of storing and transmitting data in a particular form so that only those for whom it is intended can read and process it.

How to Implement Cryptography in Python

1. Importing Modules

To perform cryptography, we will be using the cryptography module and we will be making use of the Fernet objects.

from cryptography.fernet import Fernet

2. Implementing Cryptography

To implement cryptography we will be generating a Fernet key (known as the “secret key”) and then we create a Fernet object using the key.

This key is very important and it needs to be kept safe! If someone finds your key he/she can decrypt all your secret messages and if you lose it then you will no longer be able to decrypt your own messages.

key = Fernet.generate_key()
Fernet_obj= Fernet(key)

The next step is to encrypt the text where we use the encrypt function and pass the message to the function. The function will return the encrypted message.

Along with this let’s also store the decrypted message from the encrypted message using the decrypt function and pass the encrypted message.

Encry_text = Fernet_obj.encrypt(b"I am a secret! I will get encrypted into something you will never understand")
Org_text= Fernet_obj.decrypt(Encry_text)

3. Printing Results

Now let’s have a print the encrypted and decrypted message we obtained.

print("The Encrypted text is: ", cipher_text)
print("\nThe Decrypted text is: ",plain_text)

The output looked something like what’s shown below.

The Encrypted text is:  b'gAAAAABgsSrnZRaDQbApvKL_xiXfCXHV_70u5eXZKDqYIkMKwxochYNy0lmVrvPFtQWya22MZh92rimscuA5VBuoN-B5YfCRHvpBYhKsbIiuPuz-CklJ-EFyZtZ_S7TRe-b9VSoee03Z8jkxwQpR8FatZ1XWA7xZvm5WpGSQFZkN8w7Ix8riyOo='
 
The Decrypted text is:  b'I am a secret! I will get encrypted into something you will never understand'


No comments:

Powered by Blogger.