PyCrypto: A Comprehensive Python Library for Cryptographic Algorithms!

PyCrypto: A Comprehensive Python Library for Cryptographic Algorithms!

Hello everyone! I am J, a seasoned programmer with 10 years of experience in various major companies. Recently, many friends have privately messaged me asking how to implement commonly used cryptographic algorithms in interface testing using Python. Today, I will take you on a journey to explore the treasure trove that is the PyCrypto library, which is a toolbox for cryptographic algorithms, easily handling various encryption and HASH algorithms!

Encryption, let’s get started!

First, let’s take a look at the SHA-256 algorithm. It can transform a large amount of data into a fixed-length “fingerprint”; any slight change in the data will result in a significant change in the “fingerprint”. Just like every person has a unique fingerprint, isn’t that fascinating?

 1from Crypto.Hash import SHA256
 2
 3hash = SHA256.new()
 4hash.update(b'message') # Note: This needs to be converted to bytes
 5
 6# Get the encrypted digest
 7digest = hash.digest()
 8print(digest) # Output: b'\xabS\n\x13\xe4Y\x14\x98+y\xf9\xb7\xe3\xfb\xa9\x94\xcf\xd1\xf3\xf3“\xf7\x1c\xea\xla\xf0+F\x0cm\x1d'
 9
10# Get the hexadecimal format of the digest
11hex_digest = hash.hexdigest()
12print(hex_digest) # Output: ab530a13e45914982b79f9b7e3fba994cfd1f3fb22f71cealafbf02b460cbdld

Tip: The update() method can be called multiple times to handle large files, for example: hash.update(b'part1'); hash.update(b'part2'), which is equivalent to hash.update(b'part1part2').

Next, let’s play with AES encryption. AES is one of the most popular encryption algorithms today!

 1from Crypto.Cipher import AES
 2
 3# Define the key and initialization vector IV; the key must be 16, 24, or 32 bytes, and IV must be 16 bytes
 4key = b'This is a key123'  # 16 bytes
 5iv = b'This is an IV456'   # 16 bytes
 6
 7# Create an AES encryption object
 8obj = AES.new(key, AES.MODE_CBC, iv)
 9
10message = "The answer is no"
11# The string to be encrypted must be a multiple of 16; if not, padding is required
12ciphertext = obj.encrypt(message.encode('utf-8')) # Encrypt
13print(ciphertext)
14
15# Decrypt
16obj2 = AES.new(key, AES.MODE_CBC, iv)
17plaintext = obj2.decrypt(ciphertext).decode('utf-8')
18print(plaintext)

Note: The key length must be 16, 24, or 32 bytes! The IV length must be 16 bytes! If the lengths are incorrect, the program will throw an error!

Abstraction and Unification are Key!

I have noticed that in the above two examples, although the algorithms are different, the code structure is quite similar: both first create an object and then call the update() or encrypt()/decrypt() methods. Can we abstract a universal encryption framework?

 1from Crypto.Hash import SHA256
 2from Crypto.Cipher import AES
 3
 4def encrypt_or_hash(algorithm, data, key=None, iv=None):
 5    if algorithm == 'SHA256':
 6        h = SHA256.new()
 7        h.update(data.encode('utf-8'))
 8        return h.hexdigest()
 9    elif algorithm == 'AES':
10        obj = AES.new(key, AES.MODE_CBC, iv)
11        return obj.encrypt(data.encode('utf-8'))
12    else:
13        return "Unsupported algorithm"
14
15# Example usage
16print(encrypt_or_hash('SHA256', 'message'))
17print(encrypt_or_hash('AES', 'The answer is no', key=b'This is a key123', iv=b'This is an IV456'))

Advanced Challenge, Piece of Cake!

Now, we can use this framework to solve more problems! For example, you can perform a SHA-256 check on a file or use AES to encrypt a configuration file, all easily accomplished!

1# Read file content and perform SHA256 check
2with open('my_file.txt', 'r') as f:
3    file_content = f.read()
4    hashed_content = encrypt_or_hash('SHA256', file_content)
5    print(f"File hash: {hashed_content}")

In Summary!

Today, we learned about the PyCrypto library, which allows us to easily implement various cryptographic algorithms. We also abstracted a universal encryption framework together, isn’t that impressive? After you go down, you can practice more and try to implement other cryptographic algorithms using PyCrypto. If you have any questions, feel free to leave a message in the comments, and I will reply to everyone!

Leave a Comment