| | 19 | class CryptedStorage(Storage): |
| | 20 | |
| | 21 | prefix = 'salt' |
| | 22 | |
| | 23 | def setPassword(self,password): |
| | 24 | self.password = password |
| | 25 | |
| | 26 | |
| | 27 | def decrypt(self,password,salt,text): |
| | 28 | key = str(password+salt) |
| | 29 | cipher = blowfish.Blowfish(key) |
| | 30 | cipher.initCTR() |
| | 31 | return cipher.decryptCTR(text) |
| | 32 | |
| | 33 | def encrypt(self,password,salt,text): |
| | 34 | key = str(password+salt) |
| | 35 | cipher = blowfish.Blowfish(key) |
| | 36 | cipher.initCTR() |
| | 37 | return cipher.encryptCTR(text) |
| | 38 | |
| | 39 | |
| | 40 | def save(self): |
| | 41 | data = 'opencoin'+base64.b64encode(cPickle.dumps(self.data)) |
| | 42 | salt = ''.join([str(random.randint(0,9)) for i in range(0,16)]) |
| | 43 | crypted = self.encrypt(self.password,salt,data) |
| | 44 | content = '%s%s%s' % (self.prefix,salt,base64.b64encode(crypted)) |
| | 45 | open(self.filename,'w').write(content) |
| | 46 | return self |
| | 47 | |
| | 48 | |
| | 49 | def restore(self): |
| | 50 | if os.path.exists(self.filename): |
| | 51 | content = open(self.filename).read() |
| | 52 | if content.startswith(self.prefix): |
| | 53 | salt = content[4:20] |
| | 54 | crypted = base64.b64decode(content[20:]) |
| | 55 | data = self.decrypt(self.password, salt, crypted) |
| | 56 | if data.startswith('opencoin'): |
| | 57 | data = data[8:] |
| | 58 | else: |
| | 59 | raise 'wrong password' |
| | 60 | data = base64.b64decode(data) |
| | 61 | else: |
| | 62 | data = content |
| | 63 | |
| | 64 | self.data = cPickle.loads(data) |
| | 65 | return self |
| | 66 | |
| | 67 | |
| | 68 | |
| | 69 | |