Skip to content

Commit

Permalink
dev the handler module continuing.
Browse files Browse the repository at this point in the history
  • Loading branch information
liwei-lai committed Oct 9, 2012
1 parent 8e42023 commit d8838b6
Showing 1 changed file with 55 additions and 8 deletions.
63 changes: 55 additions & 8 deletions pypw/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,9 @@
from Crypto import Random

import os
import json
import logging
import hashlib


class Handler(object):
Expand All @@ -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

Expand All @@ -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):
Expand All @@ -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:]

0 comments on commit d8838b6

Please sign in to comment.