· 6 years ago · Jul 06, 2019, 05:20 AM
1from hashlib import sha256
2
3def get_hexdigest(salt, plaintext):
4 return sha256(salt + plaintext).hexdigest()
5
6SECRET_KEY = 's3cr3t'
7
8def make_password(plaintext, service):
9 salt = get_hexdigest(SECRET_KEY, service)[:20]
10 hsh = get_hexdigest(salt, plaintext)
11 return ''.join((salt, hsh))
12
13ALPHABET = ('abcdefghijklmnopqrstuvwxyz'
14 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
15 '0123456789!@#$%^&*()-_')
16
17def password(plaintext, service, length=10):
18 raw_hexdigest = make_password(plaintext, service)
19
20 # Convert the hexdigest into decimal
21 num = int(raw_hexdigest, 16)
22
23 # What base will we convert `num` into?
24 num_chars = len(ALPHABET)
25
26 # Build up the new password one "digit" at a time,
27 # up to a certain length
28 chars = []
29 while len(chars) < length:
30 num, idx = divmod(num, num_chars)
31 chars.append(ALPHABET[idx])
32
33 return ''.join(chars)
34
35from peewee import *
36
37db = SqliteDatabase('accounts.db')
38
39class Service(Model):
40 name = CharField()
41 length = IntegerField(default=8)
42 symbols = BooleanField(default=True)
43 alphabet = CharField(default='')
44
45 class Meta:
46 database = db
47
48 def get_alphabet(self):
49 if self.alphabet:
50 return self.alphabet
51 alpha = ('abcdefghijklmnopqrstuvwxyz'
52 'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
53 '0123456789')
54 if self.symbols:
55 alpha += '!@#$%^&*()-_'
56 return alpha
57
58 def password(self, plaintext):
59 return password(plaintext, self.name, self.length)
60
61 @classmethod
62 def search(cls, q):
63 return cls.select().where(cls.name ** ('%%%s%%' % q))
64
65db.create_table(Service, True)