PageRenderTime 68ms CodeModel.GetById 34ms RepoModel.GetById 0ms app.codeStats 0ms

/config.py

https://github.com/ahri/financials
Python | 47 lines | 31 code | 11 blank | 5 comment | 8 complexity | fb315a4d2975c810254876ad12630b67 MD5 | raw file
  1. # coding: utf-8
  2. """
  3. Module for loading, updating, saving _configuration
  4. """
  5. from Crypto.Cipher import Blowfish as crypto
  6. import simplejson as json
  7. from getpass import getpass
  8. _config = {}
  9. def _get_passphrase(confirm=False, length_req=15, prompt="Passphrase"):
  10. """Get a passphrase, loop until we get what we want"""
  11. while True:
  12. p1 = getpass(prompt + ": ")
  13. if len(p1) < length_req:
  14. print "ERROR: Phrase must be longer than %d characters" % length_req
  15. continue
  16. if confirm == False:
  17. break
  18. p2 = getpass("Repeat: ")
  19. if p1 == p2:
  20. break
  21. print "ERROR: Entries do not match"
  22. return p1
  23. def load(filename):
  24. with open(filename, 'r') as cfg_file:
  25. data = cfg_file.read()
  26. crypt = crypto.new(_get_passphrase(length_req=0, prompt="Open config passphrase"), crypto.MODE_ECB)
  27. try:
  28. _config.update(json.loads(crypt.decrypt(data)))
  29. except json.decoder.JSONDecodeError:
  30. raise ValueError("Incorrect passphrase given")
  31. def save(filename):
  32. crypt = crypto.new(_get_passphrase(confirm=True, prompt="Save config passphrase"), crypto.MODE_ECB)
  33. s = json.dumps(_config)
  34. padded_size = len(s) + (crypto.block_size - len(s) % crypto.block_size)
  35. with open(filename, 'w') as cfg_file:
  36. cfg_file.write(crypt.encrypt(s.ljust(padded_size)))