20 Lines of Python Code for Encrypted Communication

20 Lines of Python Code for Encrypted Communication

1. Introduction

The internet is filled with eavesdropping, and our information can easily be obtained by malicious individuals, causing us negative impacts. If you need to transmit confidential or sensitive personal information over the internet, you may need to encrypt it to guard against prying eyes. Using online or mobile encryption software may also expose you to malicious software that could leak information. Therefore, as programmers, we can implement our own encryption system.

This article demonstrates encryption, decryption, signing, and verification functions using 20 lines of Python code. By following along, you will not only understand encryption technology but also be able to implement your own encrypted communication mechanism.

Encryption and decryption are based on advanced mathematical theories, and it is not recommended to implement encryption algorithms yourself; it is better to directly use the corresponding libraries.

2. Encryption Technology

We will demonstrate two types of encryption technology here: symmetric encryption and asymmetric encryption.

Before explaining encryption technology, we need to assume our usage scenario, which is a common setting in cryptography.

  • Alice and Bob are the two parties communicating.

  • Eve is an eavesdropper.

  • The message being transmitted is PlainText.

  • The secret key used for encryption is key.

  • The encrypted message is the secret message.

3. Simple Lock: Basic Symmetric Encryption

Symmetric encryption: both parties use the same secret key for encryption and decryption. For example, here, <span>key</span><span>=</span><span>'1234567887654321'</span><span>.</span><span>encode</span><span>(</span><span>'utf-8'</span><span>)</span>, this key is a shared secret between Alice and Bob. When Alice sends a message, he needs to perform the following operations to complete the encryption.

from Crypto.Cipher import AES
cryptor = AES.new(key, AES.MODE_ECB)
secret = cryptor.encrypt(plain.encode('utf-8'))
secret = b64encode(secret)
  • The first line imports the AES algorithm. AES is a type of symmetric encryption algorithm.

  • The second line creates a new encryptor, where the key is the secret, and <span>AES</span><span>.</span><span>MODE_ECB</span> is the information padding mode.

  • The third line completes the encryption with the encrypt function.

  • The fourth line encodes the encrypted information with b64encode and sends it to Bob.

HTTP is a text protocol, and the content is all text characters. To transmit binary files, they need to be converted to text; Base64 encoding is a way to represent binary data using text characters.

After Bob receives the information, he performs the following decoding and decryption operations.

secret = b64decode(secret)
plainText = cryptor.decrypt(secret).decode('utf-8')

The resulting plainText is the plaintext information sent by Alice.

Note that both parties use the same secret key for encryption and decryption.

Now, let’s address a small issue: network packet loss often occurs, causing Alice’s messages to sometimes be incomplete. What should we do?

4. Tamper-Proof Fingerprint: Hash Function

Just as people have fingerprints, transmitted messages also have their own fingerprints. A hash function is used to find the fingerprint of a message. A hash function, also known as a message digest function, extracts a summary from a piece of content to create a fingerprint. This output (fingerprint) has distinct characteristics:

  • No matter how long the input, the output length is fixed, and the output looks like garbled text.

  • Changing the input slightly results in a significantly different output.

  • The message can produce a fingerprint, but the fingerprint cannot produce the message.

With these characteristics, Alice can hash the message and send both the hash value and the message to Bob. Bob can also hash the message; if the two values are the same, it indicates that the message is complete and has not been tampered with or lost.

from hashlib import md5
plainText = 'I love you!'
hash_ = md5(plainText.encode('utf-8')).hexdigest()

The result is: <span>690a8cda8894e37a6fff4d1790d53b33</span>. If Bob also hashes this message and the result is the same, it indicates that the message is complete.

Now let’s tackle a big issue: if the symmetric encryption key is lost and obtained by the malicious Eve, he can easily eavesdrop on the communication between Alice and Bob and even impersonate either party to send messages to the other.

Now it’s time for asymmetric encryption to come into play.

5. The Spear and the Shield: Asymmetric Encryption

Asymmetric encryption means that the encryption and decryption keys are not the same; they are a pair. The one that you hold is called the private key, and the one given to the other party is called the public key. The characteristics are:

  • Public key encryption, private key decryption.

  • Private key encryption, public key decryption.

  • The private key can derive the public key, but not vice versa.

Using these characteristics, we can implement a secure encryption algorithm. First, Bob generates a key pair and saves them to a file.

import rsa
Bob_pubkey, Bob_privkey = rsa.newkeys(512)


with open('Bob-pri.pem', 'wb') as prif, open('Bob-pub.pem', 'wb') as pubf:
    prif.write(Bob_privkey.save_pkcs1())
    pubf.write(Bob_pubkey.save_pkcs1())

Where

  • <span>Bob_privkey</span> is Bob’s private key, which he keeps.

  • <span>Bob_pubkey</span> is Bob’s public key, which is given to others.

When Alice sends a message to Bob,

  • she uses Bob’s public key to encrypt: <span>secret</span><span>=</span><span>rsa</span><span>.</span><span>encrypt</span><span>(</span><span>plain_byte</span><span>,</span><span>Bob_pubkey</span><span>)</span>.

After Bob receives the message,

  • Bob uses his private key to decrypt the information sent by Alice: <span>plain</span><span>=</span><span>rsa</span><span>.</span><span>decrypt</span><span>(</span><span>secret</span><span>,</span><span>Bob_privkey</span><span>).</span><span>decode</span><span>(</span><span>'utf-8'</span><span>)</span>.

Bob’s public key allows Alice to send messages to Bob, and Bob uses his private key to decrypt the information sent to him. Thus, Alice and Bob achieve secure communication; they use each other’s public keys for encryption and their own private keys for decryption.

The information Alice sends to Bob cannot be decrypted by Eve, even if he intercepts it, because he does not have Bob’s private key.

However, there is a problem: what if Eve uses Bob’s public key to encrypt a message, impersonating Alice to send it to Bob? How can we determine that Alice is indeed Alice and not Eve? The key issue is that Alice holds Alice’s private key, while Eve does not; this is the basis of digital signature technology.

6. The Truth: Digital Signature

Eve impersonating Alice is like a fake monk pretending to be the real one; it may look very similar, but how do we distinguish them? It’s simple: the real monk has a core technology, which is the tightening spell.

In asymmetric encryption, public key encryption and private key decryption are usually used. If we use a private key to encrypt, it is equivalent to signing. Only the holder of the private key can encrypt, and it can be decrypted by the public key. Thus, private key encryption is equivalent to the private key holder confirming the signature — that the message comes from the holder of the private key.

The private key is like the tightening spell of the real monk.

For efficiency, we generally do not encrypt the original information directly, but rather the hashed value of it. According to the properties of hashing mentioned above, this still guarantees the uniqueness and integrity of the original information.

Encrypting the message digest with the private key is called a digital signature.

The verification steps are as follows:

  • Alice prepares to send the message PlainText.

  • First, calculate its MD5 hash value Hash_a.

  • Then encrypt the hash value with the private key (digital signature).

  • Send Alice’s public key, the digital signature, and the message to Bob.

  • After receiving the message, Bob performs the following steps:

  • Use Alice’s public key to decrypt the digital signature, producing a hash value Hash_a to verify.

  • Then calculate the hash value of the message Hash_b.

  • If Hash_a == Hash_b, it indicates that the sender must be Alice, who holds the private key, and the message has not been modified.

  • Otherwise, it indicates that the message was not sent by Alice.

signature = rsa.sign(plain_byte, Alice_privkey, 'MD5')
status = rsa.verify(plain_byte, signature, Alice_pubkey)

Note that in the above example, the sign method signs with Alice’s private key, while the verification uses Alice’s public key. Alice cannot deny signing the information because only he holds his private key, and no one else can sign (private key encryption) such information.

Just like the real monk can recite the tightening spell, this is his private key. The fake monk may look similar, but he does not know the tightening spell, so he cannot speak the truth.

7. Conclusion

This article demonstrates how to implement secure communication using 20 lines of Python code.

  • The hash function is a tool that can extract the digital fingerprint of a message, which can verify data integrity.

  • Symmetric encryption is simple and practical.

  • With the help of asymmetric encryption, we achieve secure communication, and digital signatures prevent impersonation or denial.

Author: Gong Qingkui, interested in computer and electronic information engineering.

Support the Author

20 Lines of Python Code for Encrypted Communication

20 Lines of Python Code for Encrypted Communication20 Lines of Python Code for Encrypted Communication20 Lines of Python Code for Encrypted Communication

20 Lines of Python Code for Encrypted Communication

Leave a Comment