| 1 | import UserDict, cPickle, blowfish, random, os, base64, zlib |
|---|
| 2 | class Storage(UserDict.UserDict): |
|---|
| 3 | |
|---|
| 4 | def setFilename(self,filename): |
|---|
| 5 | self.filename = filename |
|---|
| 6 | return self |
|---|
| 7 | |
|---|
| 8 | def save(self): |
|---|
| 9 | cPickle.dump(self.data,open(self.filename,'w')) |
|---|
| 10 | return self |
|---|
| 11 | |
|---|
| 12 | def restore(self): |
|---|
| 13 | try: |
|---|
| 14 | self.data = cPickle.load(open(self.filename)) |
|---|
| 15 | except: |
|---|
| 16 | pass |
|---|
| 17 | return self |
|---|
| 18 | |
|---|
| 19 | class EmptyStorage(Storage): |
|---|
| 20 | def save(self): |
|---|
| 21 | pass |
|---|
| 22 | def restore(self): |
|---|
| 23 | pass |
|---|
| 24 | |
|---|
| 25 | |
|---|
| 26 | class CryptedStorage(Storage): |
|---|
| 27 | |
|---|
| 28 | prefix = 'salt' |
|---|
| 29 | |
|---|
| 30 | def setPassword(self,password): |
|---|
| 31 | self.password = password |
|---|
| 32 | return self |
|---|
| 33 | |
|---|
| 34 | def decrypt(self,password,salt,text): |
|---|
| 35 | key = str(password+salt) |
|---|
| 36 | cipher = blowfish.Blowfish(key) |
|---|
| 37 | cipher.initCTR() |
|---|
| 38 | return cipher.decryptCTR(text) |
|---|
| 39 | |
|---|
| 40 | def encrypt(self,password,salt,text): |
|---|
| 41 | key = str(password+salt) |
|---|
| 42 | cipher = blowfish.Blowfish(key) |
|---|
| 43 | cipher.initCTR() |
|---|
| 44 | return cipher.encryptCTR(text) |
|---|
| 45 | |
|---|
| 46 | |
|---|
| 47 | def save(self): |
|---|
| 48 | #data = 'opencoin'+base64.b64encode(cPickle.dumps(self.data)) |
|---|
| 49 | data = 'opencoin'+zlib.compress(cPickle.dumps(self.data),9) |
|---|
| 50 | salt = ''.join([str(random.randint(0,9)) for i in range(0,16)]) |
|---|
| 51 | crypted = self.encrypt(self.password,salt,data) |
|---|
| 52 | #content = '%s%s%s' % (self.prefix,salt,base64.b64encode(crypted)) |
|---|
| 53 | content = '%s%s%s' % (self.prefix,salt,crypted) |
|---|
| 54 | open(self.filename,'w').write(content) |
|---|
| 55 | return self |
|---|
| 56 | |
|---|
| 57 | |
|---|
| 58 | def restore(self): |
|---|
| 59 | if os.path.exists(self.filename): |
|---|
| 60 | content = open(self.filename).read() |
|---|
| 61 | if content.startswith(self.prefix): |
|---|
| 62 | salt = content[4:20] |
|---|
| 63 | #crypted = base64.b64decode(content[20:]) |
|---|
| 64 | crypted = content[20:] |
|---|
| 65 | data = self.decrypt(self.password, salt, crypted) |
|---|
| 66 | if data.startswith('opencoin'): |
|---|
| 67 | data = zlib.decompress(data[8:]) |
|---|
| 68 | else: |
|---|
| 69 | raise Exception, 'wrong password' |
|---|
| 70 | #data = base64.b64decode(data) |
|---|
| 71 | else: |
|---|
| 72 | data = content |
|---|
| 73 | |
|---|
| 74 | self.data = cPickle.loads(data) |
|---|
| 75 | return self |
|---|
| 76 | |
|---|
| 77 | |
|---|
| 78 | |
|---|
| 79 | |
|---|