From d8838b67f83897a074bc910cc7acc413faeb565c Mon Sep 17 00:00:00 2001 From: Jason Lai Date: Tue, 9 Oct 2012 22:38:17 +0800 Subject: [PATCH] dev the handler module continuing. --- pypw/handler.py | 63 ++++++++++++++++++++++++++++++++++++++++++------- 1 file changed, 55 insertions(+), 8 deletions(-) diff --git a/pypw/handler.py b/pypw/handler.py index 9e85f5f..f8b076c 100644 --- a/pypw/handler.py +++ b/pypw/handler.py @@ -13,7 +13,9 @@ from Crypto import Random import os +import json import logging +import hashlib class Handler(object): @@ -24,11 +26,16 @@ class Handler(object): def __init__(self): # Initialize Log self.log = logging.getLogger('pypw') + # Initialize the attributes of class + self.initialized = False self.filepath = '' + self.data = None def initialize(self, cipher, filepath=None): """ validate the cipher and load the data from outside file. + + :return: True if successfully initialize, else will be False """ raise NotImplementedError @@ -38,26 +45,66 @@ def write(self): """ raise NotImplementedError - def add_item(group, item, value, update=False): + def add_record(group, record, value, update=False): raise NotImplementedError @property - def items(self): + def records(self): raise NotImplementedError + @classmethod + def figure_32Byte_key(cls, text): + sha = hashlib.sha256() + sha.update(text) + return sha.hexdigest()[::2] + class AESHandler(Handler): """ Hander use AES to encrypt/decrypt user infomations """ - def __init__(self): - self.key = b'' + def __init__(self): + self.cipher = '' + self.data = None + super(AESHandler, self).__init__() def initialize(self, cipher, filepath='records.dat'): - if not os.path.existx(filepath): - self._init_struct() - return + self.filepath = filepath + self.cipher = self.figure_32Byte_key(cipher) + + # first initial the program + if not os.path.existx(self.filepath): + self._initial_data() + self.initialized = True + return self.initialized + + # validate the cipher and load the data + with open(filepath, 'rb') as f: + ciphertext = f.read() + jsondata = self.decrypt(ciphertext, key) + try: + self.data = json.loads(jsondata) + except ValueError: + return self.initialized + + if self.data['digest'] == self.cipher: + self.initialized = True + + return self.initialized + + def _initial_data(self): + pass + + def write(self): + pass + + def add_record(group, record, value, update=False): + pass + + @property + def records(self): + pass @classmethod def encrypt(cls, plaintext, key): @@ -71,4 +118,4 @@ def decrypt(cls, ciphertext, key): iv = Random.new().read(AES.block_size) cipher = AES.new(key, AES.MODE_CFB, iv) return cipher.decrypt(ciphertext)[AES.block_size:] - +