The hashlib and base64 cryptographic modules in python use instances

  • 2020-04-02 14:01:43
  • OfStack

I've seen several bloggers learn python by knocking down modules, and I'll follow along. Here's a look at some of the modules involved in encryption in python.

hashlib

Hashlib module support encryption algorithms have md5 sha1 sha224 sha256 sha384 sha512 (please reference (link: http://msdn.microsoft.com/zh-cn/library/92f9ye3s.aspx) encryption principle), it is very easy to use.

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

One, add mode

Code example:


 import hashlib # The introduction of hashlib The module
 
 mm = hashlib.md5() # To create a md5 object
 mm.update("Hello") # through update Method to encrypt text
 mm.update(" world!") # These two sentences are equivalent to mm.update("Hello world!")
 print mm.digest() # Output encrypted binary data
 print mm.hexdigest() # Output encrypted hexadecimal data

Ii. One sentence

If you do not need to append, just encrypt a piece of text, you can use this form, code example:


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

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

For other encryption algorithms, simply replace "md5" in the code, without giving you an example.

base64

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


import base64 a = "Hello world!"
b = base64.encodestring(a) # encryption
c = base64.decodestring(b) # decryption print a==c

Python also has a number of third-party modules that provide additional encryption methods, which we'll discuss later.


Related articles: