标签:style ar color sp for 文件 on bs ad
hashlib的md5和sha1等的运用
import hashlib
print(hashlib.algorithms_available)
print(hashlib.algorithms_guaranteed)
#MD5
import hashlib
hash_object = hashlib.md5(b‘Hello World‘)
print(hash_object.hexdigest())
#
import hashlib
mystring = input(‘Enter String to hash: ‘)
# Assumes the default UTF-8
hash_object = hashlib.md5(mystring.encode())
print(hash_object.hexdigest())
#sha1
import hashlib
hash_object = hashlib.sha1(b‘Hello World‘)
hex_dig = hash_object.hexdigest()
print(hex_dig)
#sha224
import hashlib
hash_object = hashlib.sha224(b‘Hello World‘)
hex_dig = hash_object.hexdigest()
print(hex_dig)
#sha256
import hashlib
hash_object = hashlib.sha256(b‘Hello World‘)
hex_dig = hash_object.hexdigest()
print(hex_dig)
#sha384
import hashlib
hash_object = hashlib.sha384(b‘Hello World‘)
hex_dig = hash_object.hexdigest()
print(hex_dig)
#sha512
import hashlib
hash_object = hashlib.sha512(b‘Hello World‘)
hex_dig = hash_object.hexdigest()
print(hex_dig)
#new&update
import hashlib
hash_object = hashlib.new(‘DSA‘)
hash_object.update(b‘Hello World‘)
print(hash_object.hexdigest())
例:
import uuid import hashlib def hash_password(password): # uuid is used to generate a random number salt = uuid.uuid4().hex return hashlib.sha256(salt.encode() + password.encode()).hexdigest() + ‘:‘ + salt def check_password(hashed_password, user_password): password, salt = hashed_password.split(‘:‘) return password == hashlib.sha256(salt.encode() + user_password.encode()).hexdigest() new_pass = input(‘Please enter a password: ‘) hashed_password = hash_password(new_pass) print(‘The string to store in the db is: ‘ + hashed_password) old_pass = input(‘Now please enter the password again to check: ‘) if check_password(hashed_password, old_pass): print(‘You entered the right password‘) else: print(‘I am sorry but the password does not match‘)
文件的hash
#MD5 File Hash in Python import hashlib hasher = hashlib.md5() with open(‘myfile.jpg‘, ‘rb‘) as afile: buf = afile.read() hasher.update(buf) print(hasher.hexdigest()) #MD5 Hash for Large Files in Python import hashlib BLOCKSIZE = 65536 hasher = hashlib.md5() with open(‘anotherfile.txt‘, ‘rb‘) as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) print(hasher.hexdigest()) #SHA1 File Hash in Python import hashlib BLOCKSIZE = 65536 hasher = hashlib.sha1() with open(‘anotherfile.txt‘, ‘rb‘) as afile: buf = afile.read(BLOCKSIZE) while len(buf) > 0: hasher.update(buf) buf = afile.read(BLOCKSIZE) print(hasher.hexdigest())
标签:style ar color sp for 文件 on bs ad
原文地址:http://my.oschina.net/lenglingx/blog/348689