This article describes how to use the hashlib and base64 encryption modules in python. The hashlib module supports the md5sha1sha224sha256sha384sha512 encryption algorithms, if you need python, You can see several bloggers learn python by breaking through the modules. I also follow the same example. This article describes the modules involved in python encryption.
Hashlib
The hashlib module supports the md5 sha1 sha1_sha256 sha384 sha512 encryption algorithm (for details about the encryption principle, refer to here), which is easy to use.
Md5 encryption is used as an example. There are two methods:
I. append Mode
Sample Code:
The Code is as follows:
Import hashlib # introduce the hashlib Module
Mm = hashlib. md5 () # create an md5 object
Mm. update ("Hello") # encrypt text using the update Method
Mm. update ("world! ") # Append. The two sentences are equivalent to mm. update (" Hello world! ")
Print mm. digest () # output encrypted binary data
Print mm. hexdigest () # output the encrypted hexadecimal data
2. One sentence
If you do not need to append an object, you only need to encrypt a piece of text in this form. The sample code is as follows:
The Code is as follows:
Import hashlib
Hashlib. new ("md5", "Hello world! "). Digest ()
In addition, md5 and other algorithm objects provide digest_size and block_size attributes to indicate the size of the encrypted text.
For other encryption algorithms, you only need to replace "md5" in the code.
Base64
The encryption algorithm provided by this module is not secure, but is very simple and sometimes used.
Sample Code:
The Code is as follows:
Import base64
A = "Hello world! "
B = base64.encodestring (a) # Encryption
C = base64.decodestring (B) # decrypt
Print a = c
Python also has many third-party modules to provide more encryption methods.