How to Write an Encryption Program in Python?

How To Write An Encryption Program

Encryption with python is the most straightforward task, as python has a package called cryptography. This package is used to encrypt and decrypt messages.

In today’s world, where cybersecurity crimes and hacking prevail, we must be careful with sending or receiving data. Data in its purest form can be easily tapped and misused. So we must use encryption while dealing with confidential or personal data.

This tutorial will teach us about cryptography, encryption, decryption, and possible ways to write an encryption program.

What is Cryptography?

Cryptography is the transfer of messages from sender to receiver via a secure channel in the presence of a trusted third party or adversary. The messages are converted into a secret code or another form that is only known to the sender and can be decrypted by the receiver with the help of a key. This conversion ensures that no one else can get hold of the message being transferred. Cryptography involves using mathematical algorithms and keys to convert plain text into cipher text and vice versa.

Cryptography mainly focuses on confidentiality, authenticity, and integrity. The well-known use case of cryptography is for Military and government agencies.

Data transfer between higher officials of the government or the military takes place in the form of secret codes.

Applications of Cryptography

Some of the daily life applications of cryptography are given below.

  • Password protection
  • Secure Network Communications
  • Digital Signatures
  • Electronic Money

Read this article to learn more about the cryptography module

What is Encryption?

Encryption is the process of converting plain text into cipher text that is unreadable to anyone except the receiver with a key to decrypt the message.

What is Decryption?

Decryption converts cipher text back to plaintext using a decryption key or algorithm. It is the opposite process of encryption.

Here is the flow chart of the data transmission between sender and receiver, where the sender sends Hello! as a message which is then converted to a cipher text using an encryption key. The receiver decrypts the cipher text and obtains the original message using a decryption key.

Cryptography
Cryptography

How to Write an Encryption Program?

There are a few ways to write an encryption program in python. We’re going to discuss the following approaches.

  • Encryption using the ASCII code
  • Encryption using string reversal
  • Symmetric key encryption

Encryption Using the Ascii Code

The ASCII, abbreviated from American Standard Code for Information Interchange, is a character encoding standard for electronic communication. ASCII codes represent text in computers, telecommunications equipment, and other devices.

Below is the ASCII chart for reference.

ASCII
ASCII

In this approach, we will take the input from the user, get the ASCII code of each character in the message and print the cipher text with a key added to the ASCII value of each character.

Refer to this article to learn how to print the ASCII value of a character.

Let us see how we can write the program.

#encryption using the ascii code
msg = input("Enter a message to encrypt: ")
encmsg = ""
for ch in msg:
    asc = ord(ch) + 3
    ench = chr(asc)
    encmsg += ench
print("Encrypted message:",encmsg)

In the first line, we are accepting the user’s input from the keyboard using the input() function.

An empty string is created to store the encrypted message. This string is named encmsg.

In the following line, we create a for loop to iterate through every character in the msg to obtain the ASCII corresponding to that character.

asc = ord(ch) + 3: The ord() the method is used to obtain the integer value associated with a character. We are adding a key to encrypt the message. This line returns the integer value+3 point of a character. For example, if the Unicode integer value of a character is 65, this line returns the integer 68. This computation is stored in a variable called asc.

ench = chr(asc): The above line generates the integer +3 value associated with the character. But we need the character at that Unicode value to encrypt the message. The chr() method returns the character associated with the integer. This character is stored in the variable called ench.

Lastly, each character in the message is converted into a cipher text by the above two lines and is appended to the empty string we created earlier.

In the last line, we print the encrypted message stored in the variable encmsg.

The output is given below.

Encryption Using Ascii
Encryption Using Ascii

Based on the ASCII chart, the Unicode Integer value of the character H is 72. When we add the key value that is 3, it becomes 75. The character associated with the integer 75 is K. So, the encrypted message has K as its first character. The same approach is followed for all the characters in the message.

Similarly, the exclamatory mark(!) at the end of the message has an integer value of 33. Now when we add the key value, it becomes 36. The character associated with 36 in the chart is $. Hence, the last character in the output is $.

Encryption Using String Reversal

Let us make the previous approach a little complex.

In this method, we will follow the same steps as in the previous approach but reverse the encrypted message at the end.

Let us see how we can do that.

#encryption using the ascii code
msg = input("Enter a message to encrypt: ")
encmsg = ""
for ch in msg:
    asc = ord(ch) + 3
    ench = chr(asc)
    encmsg += ench
encmsg= encmsg[::-1]
print("The encrypted message is:",encmsg)

Observe the eighth line. We have taken the encrypted message(encmsg) and applied reversal on it with the help of the slicing operator.

Visit this article to learn more about string reversal in python.

Let us see the output.

Encryption Using String Reversal
Encryption Using String Reversal

If you compare the two outputs, the encrypted message is the same. But, the order of arrangement is the opposite.

The above-discussed methods do not provide promising encryption for the data. Let us learn about other secure methods to encrypt the message.

Symmetric Key Encryption

In symmetric key encryption, only one key is used for encryption and decryption. The key used in this type of encryption is called a secret key.

The secret key that the sender and receiver use could be a specific code or a random string of letters or numbers produced by a random number generator. Symmetric key encryption can provide secrecy but cannot ensure authenticity.

In this approach, we will look at Fernet the algorithm available in the cryptography module and generate a key using the fernet object.

But first, you need to install the cryptography package.

!pip install cryptography

Once you have installed it, you can now import the Fernet object.

Let us see the code.

from cryptography.fernet import Fernet
key=Fernet.generate_key()
fer=Fernet(key)
msg=fer.encrypt(b"I'm sure you will never understand this message!")
ciphmsg=fer.decrypt(msg)
orgmsg=ciphmsg.decode()
print("The original message is:\n",orgmsg)
print("The encypted message is:\n",msg)
print("The cipher text is:\n",ciphmsg)

from cryptography.fernet import Fernet: Fernet is a class of the cryptography.fernet module. We are importing the Fernet class in this line.

key=Fernet.generate_key(): We are generating an encryption key that will be used to encrypt the message. This encryption key is stored in a variable called key

fer=Fernet(key): We are creating a new variable fer for storing an instance of the key generated earlier.

msg=fer.encrypt(b”I’m sure you will never understand this message!”): The message we are trying to encrypt is “I’m sure you will never understand this message! This message is stored in a variable called msg. The encrypt() method is used to encode the message. This message is then converted into bytes which are represented by the ‘b’ in front of the message as a prefix

ciphmsg=fer.decrypt(msg): The message encrypted earlier is now being decrypted using the decrypt() method. As seen in the previous line, the message is converted into bytes. So by default, the decrypted message will also be in the form of bytes. This message is stored in a variable called ciphmsg.

orgmsg=ciphmsg.decode(): The byte form of the decrypted message is now converted into readable text with the help of decode(). orgmsg is a variable created for storing the message after conversion.

In the following three lines, we are printing the original message we have given, the encrypted form, and finally, the cipher text.

Encryption Using Symmetric Key
Encryption Using Symmetric Key

Conclusion

Even though cryptography is hard, it is always considered safe to send messages to trusted receivers through cryptic and secret codes that might be useful in a data breach. Sending or receiving encrypted messages can also ensure confidentiality, integrity, and security. Cryptography is not a royal technology anymore. To protect and secure our data and information, we can also implement the methods and algorithms of cryptography in our daily life.

In this post, we have seen the definitions of cryptography, encryption, and decryption and a flow chart of data transmission with the help of encryption and decryption keys.

Coming to the encryption programs, we have learned how to encrypt our messages using Unicode Integer and character values using the ASCII protocols.

We have also observed a reversal of the message as an approach to encrypt the message.

But these methods do not guarantee a perfect encryption mechanism.

Hence, we have learned the module’s usage and installation and how to perform symmetric key encryption using the algorithms available in the package.

We have tried using the Fernet algorithm for symmetric key encryption, which uses only one key for encryption and decryption.

References

To learn more about the cryptography package, visit this official site of PyPI.