def generate_crypto(self): self.crypto = Crypto() self.keyloader = KeyLoader() self.load_keys()
class Settings(ConfigurationConsumer): '''Singleton-ish object which holds information about this user''' def __init__(self, alias): self.alias = alias self.get_uid() self.generate_crypto() def generate_crypto(self): self.crypto = Crypto() self.keyloader = KeyLoader() self.load_keys() def get_uid(self): '''Load UID from users.json or create it''' users_filename = self.config_path('users.json') users = json.load(open(users_filename,'r')) try: self.uid = users[self.alias] except Exception as msg: self.uid = self.generate_uid(32) Display.warn('Generated New UID: {0}'.format(self.uid)) users[self.alias] = self.uid with open(users_filename,'w') as out: json.dump(users, out) def generate_uid(self, size=6, chars=string.ascii_uppercase+string.digits): '''Randomly generate a UID for this user''' return ''.join(random.choice(chars) for x in range(size)) def generate_keys(self): '''Generate new RSA-2048 keys for this client (accurate off)''' Display.log('Generating new keys...') self.crypto.generate() self.save_keys() Display.log('Done.\n') def load_keys(self): '''Load public and private key from key.json; generates if empty''' filename = self.config_path('.data/{0}.pyna'.format(self.uid)) if not os.path.isfile(filename): self.generate_keys() return self.password_loop(filename) def password_loop(self, filename): '''Loops until the correct password is entered''' attempts = 0 while attempts < 3: password = input('Please enter password to unlock ({0} attempts remaining): '.format(3-attempts)) try: with open(filename,'rb') as enc_data: encrypted = pickle.load(enc_data) data = self.keyloader.unlock_with_password(password, encrypted) self.crypto.load(data['privateKey']) Display.log('User settings loaded.') return except: Display.warn('Wrong password') attempts += 1 Display.error('You have exceeded the number of attempts to log in as this user.') sys.exit(1) def save_keys(self): '''Save public and private key to key.json''' password = input('Please enter password to lock: ') privout = self.crypto.private.exportKey('PEM').decode('utf-8') data = json.dumps({"privateKey":privout}) locked = self.keyloader.lock_with_password(password, data) keyfile = self.config_path('.data/{0}.pyna'.format(self.uid)) with open(keyfile,'wb') as auth: pickle.dump(locked, auth)
def createCrypto(self): self.crypto = Crypto() self.keyloader = KeyLoader() self.loadKeys()