这是昨晚写的一段关于密码处理的代码,包含生成 salt、加密密码、生成随机密码和检验密码。结果今天懒得用了,主要是懒得写修改密码、重设密码、找回密码这些页面,于是就用 Google 的 OAuth 代替了。感觉删了也可惜,以后说不定会用到,就放这吧。至于 Model 和 StringProperty 就不要管了,和 GAE 的类似。用 Base64 是因为我会保存成 JSON 格式,否则直接用二进制的字符串即可
from base64 import b64encodefrom hashlib import sha1import hmacfrom os import urandomimport randomimport stringSPECIAL_CHARS = '!@#$%^&*()'PASSWORD_CHARS = string.ascii_letters + string.digits + SPECIAL_CHARSclass Admin(Model): name = StringProperty(required=True) password = StringProperty(required=True) salt = StringProperty(required=True) @staticmethod def encrypt_password(password, salt): return b64encode(hmac.new(password, salt, sha1).digest()).rstrip('=') def set_password(self, password): self.salt = b64encode(urandom(9)) self.password = self.encrypt_password(password, self.salt) def verify_password(self, password): return self.password == self.encrypt_password(password, self.salt) @classmethod def generate_password(cls): # 生成包含大小写字母、数字和特殊字符的 8 位密码 system_random = random.SystemRandom() random_lowercase = system_random.choice(string.ascii_lowercase) random_uppercase = system_random.choice(string.ascii_uppercase) random_digit = system_random.choice(string.digits) random_special = system_random.choice(SPECIAL_CHARS) random_others = system_random.sample(PASSWORD_CHARS, 4) password = [random_lowercase, random_uppercase, random_digit, random_special] + random_others system_random.shuffle(password) return ''.join(password)
原文地址:记录一段关于密码处理的 Python 代码, 感谢原作者分享。 我知道我不是一个很好的记录者,但我比任何人都喜欢回首自己来时的路,