我从Python和面向对象编程开始我的冒险。
我写了一个盐渍和散列密码脚本。我的主要目标是使用OOP,而不是密码学。我知道没有错误处理。
不知道如何改进我的代码,使之更面向对象。如果一个更有经验的人能看一看,并给我一些如何使它变得更好的建议,那就太好了。对新手的任何帮助都是很棒的!
描述:
这个脚本在现实生活中并不真正有用。
第一部分:哈希和salt密码以及添加salt的下一个编码到base64 (未来比较哈希所需的)。算法: base64( SHA256(密码+ salt) + salt) Salt是X随机字节,可以指定X,但默认情况下是16。
第二部分(某种授权):比较输入散列(e.x )。(从数据库)使用新创建的散列从输入的普通密码。新的salt是从输入哈希中提取的salt创建的。
代码:
import base64
import hashlib
import os
class Hashing(object):
# base64( SHA256(password + salt) + salt)
# generate new salt (default 16 bytes)
def generate_new_salt(self, salt_ln=16):
self.new_salt = os.urandom(salt_ln)
print(f'new salt: {self.new_salt}')
return self.new_salt
# get salt from hash
def get_old_salt(self, input_hash, salt_ln=16):
self.old_salt = base64.b64decode(input_hash)[-salt_ln:]
print(f'old salt: {self.old_salt}')
return self.old_salt
# compute hash using parameters
def compute_hash(self, password, salt):
self.salt = salt
self.enc_password = password.encode()
# hashing SHA256(password + salt)
hash_object = hashlib.sha256(self.enc_password + salt)
# add salt to hash and encode to base64
hash_b64 = base64.b64encode(hash_object.digest() + salt)
print(f'new_hash: {hash_b64}')
return hash_b64
# create hash from new or old salt
def create_hash(self, password, salt_ln=16,old_salt=None):
if old_salt: #if old salt then use it
self.salt = old_salt
else: #else generate new salt
self.salt = Hashing().generate_new_salt(salt_ln)
hash = Hashing().compute_hash(password, self.salt)
return hash
# compare input hash with created using salt get from input
def compare_hashes(self, password, old_hash, salt_ln=16):
self.enc_password = password.encode()
#get salt from input hash
self.old_salt = Hashing().get_old_salt(old_hash, salt_ln)
#recreat input hash
re_hash = Hashing().create_hash(password,salt_ln, self.old_salt)
print(f'Compare: old_hash: {old_hash}')
print(f'Compare: new_hash: {re_hash}')
#compare
if re_hash.decode() == old_hash.decode():
return True
else:
return False
#code below is just for testing
NewSalt = Hashing().generate_new_salt()
Hash = Hashing().create_hash('pass')
OldSalt = Hashing().get_old_salt(Hash)
CompareHash = Hashing().compare_hashes('pass', Hash)
if CompareHash:
print('HASHES THE SAME')
else:
print('NOT THE SAME')
print(CompareHash)
问题:
salt_ln = 16
)时遇到了问题。对我来说,当它在每种方法中被复制时,它看起来并不好看。有什么办法让它更全球化吗?发布于 2020-01-29 00:27:35
https://codereview.stackexchange.com/questions/236314
复制相似问题