PageRenderTime 59ms CodeModel.GetById 36ms RepoModel.GetById 0ms app.codeStats 0ms

/common/cryptocipher.py

https://github.com/dahool/vertaal
Python | 69 lines | 45 code | 3 blank | 21 comment | 8 complexity | 6710e8ffa9a32b94af82f844e737b32d MD5 | raw file
  1. """Copyright (c) 2009, Sergio Gabriel Teves
  2. All rights reserved.
  3. This program is free software: you can redistribute it and/or modify
  4. it under the terms of the GNU General Public License as published by
  5. the Free Software Foundation, either version 3 of the License, or
  6. (at your option) any later version.
  7. This program is distributed in the hope that it will be useful,
  8. but WITHOUT ANY WARRANTY; without even the implied warranty of
  9. MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  10. GNU General Public License for more details.
  11. You should have received a copy of the GNU General Public License
  12. along with this program. If not, see <http://www.gnu.org/licenses/>.
  13. """
  14. from random import randrange
  15. import base64
  16. from Crypto.Cipher import Blowfish
  17. from django.conf import settings
  18. class BCipher:
  19. def __init__(self, pwd=None):
  20. if not pwd:
  21. pwd = getattr(settings, 'SECRET_KEY')
  22. self.__cipher = Blowfish.new(pwd)
  23. def encrypt(self, text):
  24. ciphertext = self.__cipher.encrypt(self.__pad_file(text))
  25. return base64.b64encode(ciphertext)
  26. def decrypt(self, b64text):
  27. try:
  28. ciphertext = base64.b64decode(b64text)
  29. except TypeError:
  30. # text is not encrypted
  31. return b64text
  32. cleartext = self.__depad_file(self.__cipher.decrypt(ciphertext))
  33. return cleartext
  34. # Blowfish cipher needs 8 byte blocks to work with
  35. def __pad_file(self, text):
  36. pad_bytes = 8 - (len(text) % 8)
  37. # try to deal with unicode strings
  38. asc_text = str(text)
  39. for i in range(pad_bytes - 1):
  40. asc_text += chr(randrange(0, 256))
  41. # final padding byte; % by 8 to get the number of padding bytes
  42. bflag = randrange(6, 248); bflag -= bflag % 8 - pad_bytes
  43. asc_text += chr(bflag)
  44. return asc_text
  45. def __depad_file(self, text):
  46. pad_bytes = ord(text[-1]) % 8
  47. if not pad_bytes: pad_bytes = 8
  48. return text[:-pad_bytes]
  49. if __name__ == '__main__':
  50. print "INIT TEST"
  51. key = '%8%z7z3&*8*3t^h@j!!z953js5!3h^g%+1m9xcr17e!%dqb+2w'
  52. text = "este es un TEXTO que hay que encriptar"
  53. print "ENCRYPT: %s" % text
  54. bc = BCipher(key)
  55. crypt = bc.encrypt(text)
  56. print "RESULT: %s" % crypt
  57. res = bc.decrypt(crypt)
  58. print "DESCRYPTED: %s" % res
  59. if res == text:
  60. print "Success"
  61. else:
  62. print "Fail"