Skip to content

Commit

Permalink
commit codes and some bugs need to be fix.
Browse files Browse the repository at this point in the history
  • Loading branch information
liwei-lai committed Oct 12, 2012
1 parent 301b154 commit 281f723
Showing 1 changed file with 46 additions and 30 deletions.
76 changes: 46 additions & 30 deletions pypw/handler.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,16 +9,16 @@
:license: BSD, see LICENSE for more details.
"""

from Crypto.Cipher import AES
from Crypto import Random

import os
import json
import logging
import hashlib
from datetime import datetime
from collections import defaultdict

from Crypto.Cipher import AES
from Crypto import Random


class AESHandler(object):
"""
Expand All @@ -34,9 +34,9 @@ def __init__(self):
self.filepath = ''
self.cipher = ''
self.data = None
# self.records is a proxy structure mapping to the records of
# self._records is a proxy structure mapping to the records of
# self.data and is use for better contrive records.
self.records = defaultdict(dict)
self._records = defaultdict(dict)

def initialize(self, cipher, filepath='records.dat'):
"""
Expand All @@ -48,22 +48,24 @@ def initialize(self, cipher, filepath='records.dat'):
self.cipher = self.figure_32Byte_key(cipher)

# first initial the program
if not os.path.existx(self.filepath):
self.data = compose_structure(cipher)
if not os.path.exists(self.filepath) or \
not os.path.getsize(self.filepath):
# initiali the self.data and self._records
self._init_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)
jsondata = self.decrypt(ciphertext, self.cipher)

try:
self.data = json.loads(jsondata)
if self.data['digest'] == self.cipher:
self.initialized = True
# initiali the self.data and self.records
self._init_data()
# initiali the self._records
self._setup_structure()
except ValueError:
self.log.error('Error occur when load the JSON text.')
except Exception, err:
Expand All @@ -73,34 +75,42 @@ def initialize(self, cipher, filepath='records.dat'):

def write(self):
"""
encrypt the infomations and dumps into outside file.
encrypt the infomations and dump into outside file.
"""
jsontext = json.dumps(self.data)
with open(self.filepath, 'w') as f:
ciphertext = self.encrypt(jsontext, self.cipher)
f.write(ciphertext)

def add_record(group, item, value, note):
def add_record(self, group, item, value, note=None):
try:
record = self._compose_record(group, item, value, note)
self.data['records'].append(record)
self.data['currentID'] += 1
self.data['currentGID'] += 1
if not self._records['gid'].has_key(record['gid']):
self.data['currentGID'] += 1
self.write()
self._adjust_structure(record)
return True
except Exception, err:
self.log.error('Error occur in adding record - %s', err)
raise
return False
return True

def update_record(group, item, value, note):
try:
# TODO: complete the method
self.write()
except Exception, err:
self.log.error('error occur in updating record - %s', err)
def update_record(self, group, item, value, note=None):
if self._records.has_key(group) and self._records[group].has_key(item):
try:
record = self._records[group][item]
record['value'] = value
if note:
record['note'] = note
self.write()
return True
except Exception, err:
self.log.error('Error occur in updating record - %s', err)
return False
else:
return False
return True

@property
def records(self):
Expand All @@ -121,19 +131,19 @@ def _setup_structure(self):
self._adjust_structure(record)

def _adjust_structure(self, record):
rid = record['id']
gid = record['gid']
rid, gid = record['id'], record['gid']
group = record['group']
item = record['itemname']
self.records['rid'][rid] = record
self.records['gid'].setdefault(gid, []).append(record)
self.records[group][item] = record
self._records['rid'][rid] = record
self._records['gid'].setdefault(gid, []).append(record)
self._records[group][item] = record

def _compose_record(group, item, value, note=None):
def _compose_record(self, group, item, value, note=None):
created = datetime.today().isoformat('_')
# TODO: should judge the correct gid
record = {
'id': self.data['currentID'] + 1,
'gid': self.data['currentGID'] + 1,
'id': self.data['currentID'],
'gid': self.data['currentGID'],
'group': group,
'itemname': item,
'value': value,
Expand All @@ -147,7 +157,13 @@ def _compose_record(group, item, value, note=None):
def figure_32Byte_key(cls, text):
sha = hashlib.sha256()
sha.update(text)
return sha.hexdigest()[::2]
digest = sha.hexdigest()[::2]

if len(text) > 32:
return digest
else:
keystr = text + digest
return keystr[:32]

@classmethod
def encrypt(cls, plaintext, key):
Expand Down

0 comments on commit 281f723

Please sign in to comment.