Hey Guys!!..
We use encryption in many applications like - Chat apps, etc.
Previous tutorials in "Learn Cryptography" series:
Here, we will cover Symmetric encryption.
Follow the installation here
There are 2 types of ciphers used - Block and Stream.
Let's use the simplest algorithm first i.e. DES.
Data Encryption Standard (DES) is a symmetric encryption algorithm.
In the image above, it is described:
Install an additional library for DES algorithm using pip in cmd as follows:
pip install pydes
For more, refer here
Performance:The code (of this package) is not written for speed or performance, so not for those needing a fast DES implementation, but rather a handy portable solution ideal for small usages. The speed at which pyDes encrypts/decrypts is around 10Kb/s (using the DES method) - that's very SLOW!!
# import the DES library using a customized package
import pyDes
# import this library for generating random number by the system
import os
# input
i = input("Enter any string: ")
# Padding function: add ' ' until the string length is multiples of 8
def padded_text(s):
while len(s)%8 !=0 :
s += ' '
return s
p = padded_text(i)
There are different modes of generating keys -
The message is divided into blocks, and each block is encrypted separately.
# key should be 8 bytes long.
k_ecb = pyDes.des("DESCRYPT", pyDes.ECB, "\0\0\0\0\0\0\0\0", pad=None, padmode=None)
# encrypted data i.e. in bytes
e_ecb = k_ecb.encrypt(str.encode(p))
print("\n The encrypted string(in bytes) - \n", e_ecb)
# extract the input text from the encrypted input using decryption
d_ecb = k_ecb.decrypt(e_ecb)
print("\n The actual input(in bytes) - \n", d_ecb)
each block of plaintext is XORed with the previous ciphertext block before being encrypted.
Initialisation vector IV can be done using
os.urandom(8) # 8-bytes in this case
When generating random data for use in cryptographic operations, such as an initialization vector for encryption in CBC mode, you do not want to use the standard random module APIs. This is because they do not provide a cryptographically secure random number generator, which can result in major security issues depending on the algorithms in use.
Therefore, it is our recommendation to always use your operating system鈥檚 provided random number generator, which is available as os.urandom().
# key should be 8 bytes long. IV vector given some random value (8 bytes for XOR operation).
k_cbc = pyDes.des("DESCRYPT", pyDes.CBC, os.urandom(8), pad=None, padmode=None)
# encrypted data i.e. in bytes
e_cbc = k_cbc.encrypt(str.encode(p))
print("\n The encrypted string(in bytes) - \n", e_cbc)
# extract the input text from the encrypted input using decryption
d_cbc = k_cbc.decrypt(e_cbc)
print("\n The actual input(in bytes) - \n", d_cbc)
For more, read here.
Triple DES (3DES) is an improved version of DES.
It is secure. key-length is long in this case.
See Wiki
applies the DES cipher algorithm three times to each data block.
That's it for now.