SoFunction
Updated on 2024-10-29

Example of using hashlib and base64 cryptographic modules in python

Having seen several bloggers learn python by going through the modules individually, I'm going to follow suit and talk about the modules involved in encryption in python in this post.

hashlib

The encryption algorithms supported by the hashlib module are md5 sha1 sha224 sha256 sha384 sha512 (for the encryption principle, please refer to thehere (literary)) and easy to use.

In the case of md5 encryption, for example, there are two methods:

I. Additional modalities

Code Example:

Copy Code The code is as follows.

import hashlib #Introduce hashlib module
 
mm = hashlib.md5() #create an md5 object
("Hello") #Encrypted text via update method
(" world!") #Append, these two sentences are equivalent to ("Hello world!")
print () #Output the encrypted binary data
print () # Output the encrypted hexadecimal data

II. One sentence

If you don't need to append, just encrypt a piece of text, you can use this form, code example:

Copy Code The code is as follows.

 import hashlib
 
 ("md5","Hello world!").digest()

In addition, algorithm objects such as md5 provide attributes such as digest_size and block_size that indicate the size of the encrypted text.

For other encryption algorithms, just replace "md5" in the code, no more examples.

base64

The encryption algorithm provided by this module is not secure, but is very simple and is sometimes used.
Code Example:

Copy Code The code is as follows.

import base64

a = "Hello world!"
b = (a) #Encryption
c = (b) #Decrypt

print a==c


Python also has a number of third-party modules that provide more encryption methods, which we'll talk about later when we learn more.