In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-19 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article is to share with you about the role of the hashlib module in Python, the editor thinks it is very practical, so I share it with you to learn. I hope you can get something after reading this article.
One: introduction to hashlib
1. What is hash: hash is an algorithm (different hash algorithms have different complexity) (3.x replaces md5 module and sha module, mainly provides SHA1, SHA224, SHA256, SHA384, SHA512, MD5 algorithm). This algorithm accepts the incoming content and gets a string of hash values after operation.
2. The characteristics of hash value are (hash value / product has three characteristics:):
2.1. As long as the content passed in is the same, the hash value must be the same = > the integrity check of the password file to be transmitted in clear text
2.2. Cannot be reduced from hash value to content = "make password into hash value. Plaintext passwords should not be transmitted on the network (only content returns hash value)."
2.3. as long as the hash algorithm is unchanged, the length of the hash value obtained is fixed no matter how big the verification content is (for example, hash check is required for downloading files from the Internet to ensure that there is no packet loss in network transmission)
Checking the consistency of file downloads based on 2.1 and 2.3
User passwords can be encrypted based on 2.1 and 2.2
The hash algorithm is like a factory that receives the raw materials you send (you can use m.update ()
Transporting raw materials for the factory), the processed product is the hash value
PS: if you need Python learning materials, you can add the group below to go to the free administrator to get it.
Second: encrypt the specified "string". Step-by-step parsing using hashlib
1) before performing md5 hashing, the data needs to be encoded, otherwise an error will be reported.
Import hashlibobj = hashlib.md5 () # construct a hashlib object obj.update ("pony crossing") # update encrypts the specified string print (obj)-result: obj.update ("pony crossing") TypeError: Unicode-objects must be encoded before hashing
2) obj is a hash object
Import hashlibobj = hashlib.md5 () obj.update ("pony crossing the river" .encode ("utf-8") print (obj,type (obj))-result:
3)
Import hashlibobj = hashlib.md5 () obj.update ("pony crossing the river" .encode ("utf-8") result=obj.hexdigest () print (result)-result: 24f67b0f6d02adc8867d612e0e0fc40a
4) add difficulty to encryption
Import hashlibobj = hashlib.md5 ("mcw@xiaoma@aaaafffff" .encode ("utf-8")) # add something to increase the complexity of encryption. The string here should also be encoded first. Obj.update ("pony crossing" .encode ('utf-8')) result = obj.hexdigest () print (result)-result: b11740508f28e04837f2c0e3a58cf990
5) use hashlib to make encryption function (add basic characters)
Import hashlibdef get_md5 (data): # pass parameter for the string to be encrypted obj = hashlib.md5 ("sidrsicxwersdfsaersdfsdfresdy54436jgfdsjdxff123ad" .encode ('utf-8')) obj.update (data.encode (' utf-8')) result = obj.hexdigest () return resultval = get_md5 ('123') print (val)-result: 35093270b6352fa9721370b781f7b4d7 3: application scenario case: user account password login Encrypt plaintext passwords import hashlibUSER_LIST = [] def get_md5 (data): obj = hashlib.md5 ("12: Idrsicxwersdfsaersdfsdfresdy54436jgfdsjdxff123ad ".encode ('utf-8') obj.update (data.encode (' utf-8')) result = obj.hexdigest () return resultdef register (): print ('* user registration *') while True: user = input ('Please enter user name:') if user = = 'user name:' Return pwd = input ('Please enter password:') temp = {'username':user 'password':get_md5 (pwd)} USER_LIST.append (temp) def login (): print (' * user login *') user = input ('Please enter user name:') pwd = input ('Please enter password:') for item in USER_LIST: if item ['username'] = = user And item ['password'] = = get_md5 (pwd): return Trueregister () result = login () if result: print (' login successful') else: print ('login failed')-result: * user registration * Please enter User name: pony crossing river Please enter password: 123456 Please enter user name: N* user login * Please enter user name: pony crossing river Please enter password: 123456 login successful user login scenario analysis: achieve user registration Then carry on the code analysis of the user login.
Code analysis:
Fourth, verify the consistency of files (how to ensure that the downloaded files do not lose packets and ensure the integrity of the downloaded data)
#-File consistency check -''you can copy a file on two different disks, and then determine whether the hash values of the two files are equal Determine whether two files are the same file''import hashlibm = hashlib.md5 () with open (r'G:/logging module with .png', 'rb') as f: for line in f: m.update (line) print (m.hexdigest ()) # 47a6b079cc33a4f312786b46e61e0305import hashlibm = hashlib.md5 () with open (r'H:/logging module with .png' 'rb') as f: for line in f: m.update (line) print (m.hexdigest ())
5. Encrypt the plaintext password
# Application: encrypt the plaintext password (brute force cracking-use the plaintext password to calculate a hash value with an algorithm, compare it with the intercepted hash value, and match the successful plaintext password, you can crack the user's password.) if the user registers information on a website, it prevents the information from being maliciously intercepted and obtained, and the user's plaintext password can be encrypted. Save it in the form of hash, so that users enter a clear text password each time they log in. Check the hash value to''password=input (' >:'). Strip () import hashlibm=hashlib.md5 () m.update (password.encode ('utf-8')) print (m.hexdigest ()) # 00dcbdaede875d5e23f1f9f64c7849ef# salt the password (password)-further enhance the security of the password password=input (' >:'). Strip () import hashlibm=hashlib.md5 () m.update ('line of egrets green Days' encode ('utf-8')) # add salt to the password m.update (password.encode (' utf-8'))
Crack the password registered by the user
# key''simulated crash library' 'import hashlibpasswds= [# can be implemented through random to the contents of passwds' alex3714', 'alex1313',' alex94139413', 'alex123456',' 123456alpha, 'a123lexicon,] def make_passwd_dic (passwds): # through plaintext password list Create the corresponding hash dictionary dic= {} for passwd in passwds: m=hashlib.md5 () # use the md5 algorithm to build a factory m.update (passwd.encode ('utf-8')) # deliver raw materials to the factory (that is, what we want to encrypt) dic [passwd] = m.hexdigest () # output hash value (that is, the final product) Add it to our pre-created empty dictionary in the form of {password: hash value} return dicdef break_code (cryptograph,passwd_dic): # to determine whether the intercepted hash value is equal to the pre-created hash value in the dictionary If it is equal, it means that we have successfully cracked for KJ v in passwd_dic.items (): if v = cryptograph: print ('password is = = >\ 033 [46m%s\ 033 [0m'% k) cryptograph='aee949757a2e698417463d47acac93df' # We intercepted the password we got, and the encrypted hash value break _ code (cryptograph,make_passwd_dic (passwds)) # the password to be cracked And the pre-made dictionary of hash is passed to the corresponding parameter as the argument of the function.
7. The encryption mode of hmac module is similar to that of hashlib
Python also has a hmac module that further processes our creation of key and content internally and then encrypts it:''import hmach = hmac.new (' King cover Tiger '.encode (' utf8')) # hmac must add salt h.update ('hello'.encode (' utf8')) print (h.hexdigest ()) # 1abaae8f65f68f2695a8545c5bc8e738# to ensure that the final results of hmac are consistent It must be guaranteed that the initial key specified in # 1:hmac.new parentheses is the same # 2: no matter how many times the update is added, the content of the check adds up to the same content # the result obtained by the single way below is the same import hmach2=hmac.new (bounded tom') # the initial value must be consistent The final result will be different. H2.update (bounded hello') h2.update (bounded world') print (h2.hexdigest ()) h3=hmac.new (baked tom') # the initial value must be consistent, and the final result will be different. H3.update (baked helloworld') print (h3.hexdigest ()) h4=hmac.new (bounded tomhelloworld') # initial value is different So it is different from the results of the above two kinds of print (h4.hexdigest ()) '0426ccec3b134e8c18fdcephal841ef250426ccec3b134e8c18fdcephal841ef25ff1214d895bbaf5f1847db4ebae8212eThe above is what the function of hashlib module in Python is. The editor believes that there are some knowledge points that we may see or use in our daily work. I hope you can learn more from this article. For more details, please follow the industry information channel.
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.