First, let's introduce the concept of MD5 and SHA1.
MD5
The full name of MD5 is message-digest algorithm 5 (Information-Digest algorithm). 128-bit length. At present, MD5 is an irreversible algorithm.
It has high security. It corresponds to any string that can be encrypted into a unique fixed-length code.
SHA1
The full name of SHA1 is secure Hash algorithm (Secure Hash algorithm). SHA1 based on MD5, the data length is longer after encryption,
It produces a hash value of 160bit in length for inputs that are less than 264 in length. 32 more bits than MD5.
Therefore, it is more secure than MD5, but SHA1 is slower than MD5.
Using MD5 and SHA1 in Python
Python's built-in module Hashlib comes with MD5, SHA1 so it's handy to use both encryption in Python.
Examples of MD5 use:
1 from Import MD5 2 " Hello World " 3 hash_md5 = MD5 (DATA_STR). Hexdigest ()4print hash_md5
The result is: 5EB63BBBE01EEED093CB22BB8F5ACDC3
Examples of SHA1 use:
1 from Import SHA1 2 " Hello World " 3 hash_sha1 = SHA1 (DATA_STR). Hexdigest ()4print HASH_SHA1
The result is: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
As you can see, the same string, the result of SHA1 after encryption is longer than the result of MD5 in length. Identical strings, the same cryptographic strings generated by the same encryption algorithm are identical.
Not only can they be used to encrypt strings, they can often also be used as filenames, as keys stored in the key value format, instance IDs that are generated by running tasks, and so on.
Generate a random string using MD5 + os.urandom (n)
There is a time when we will need to generate a globally unique ID, and this time, MD5 + Os.urandom will come in handy.
Os.urandom (n) is a method of randomly generating n-byte strings, and each generates a different value. Together with MD5 's processing, it can be a string of the same length as the content.
Example:
Import OS from Import MD5 for in range :print MD5 (os.urandom). Hexdigest () Output Result: 3c0919ae5c84adc230a7adbb90446913569c086e2f8badaf64065978ccb584823fa55d4a2a0de854bac9d33c730b742491b4a5029980a8166e30 5fe7d785b5d7b251e79ec54c7f0320bb41320b8c603379c78471e6d87ba7dc11cb40618b2cf8c14a40bb41e2ce4311d27b1add3af843148340f61bd21 93fa9fa1151f7ba7159f3d2084ee4df18e6ad03a13ac6857f472f027d38265ec0576edb0c1d24eb6f68
Python MD5 and SHA1 encryption, MD5 + OS.URANDOM generate globally unique ID