crypto_engine.py 7.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236
  1. # ============================================================================
  2. # This file is part of Pwman3.
  3. #
  4. # Pwman3 is free software; you can redistribute it and/or modify
  5. # it under the terms of the GNU General Public License, version 2
  6. # as published by the Free Software Foundation;
  7. #
  8. # Pwman3 is distributed in the hope that it will be useful,
  9. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  10. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  11. # GNU General Public License for more details.
  12. #
  13. # You should have received a copy of the GNU General Public License
  14. # along with Pwman3; if not, write to the Free Software
  15. # Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
  16. # ============================================================================
  17. # Copyright (C) 2014 Oz Nahum <nahumoz@gmail.com>
  18. # ============================================================================
  19. from __future__ import print_function
  20. from Crypto.Cipher import AES
  21. from Crypto.Protocol.KDF import PBKDF2
  22. import base64
  23. import os
  24. import sys
  25. import binascii
  26. from pwman.util.callback import Callback
  27. import pwman.util.config as config
  28. if sys.version_info.major > 2: # pragma: no cover
  29. raw_input = input
  30. EncodeAES = lambda c, s: base64.b64encode(c.encrypt(s))
  31. DecodeAES = lambda c, e: c.decrypt(base64.b64decode(e)).rstrip()
  32. def get_digest(password, salt):
  33. """
  34. Get a digest based on clear text password
  35. """
  36. iterations = 5000
  37. return PBKDF2(password, salt, dkLen=32, count=iterations)
  38. def authenticate(password, salt, digest):
  39. """
  40. salt and digest are stored in a file or a database
  41. """
  42. dig = get_digest(password, salt)
  43. return binascii.hexlify(dig) == digest
  44. def write_password(reader=raw_input):
  45. """
  46. Write a secret password as a hash and the salt used for this hash
  47. to a file
  48. """
  49. salt = base64.b64encode(os.urandom(32))
  50. passwd = reader("Please type in the secret key:")
  51. key = get_digest(passwd, salt)
  52. f = open('passwords.txt', 'wt')
  53. hpk = salt+'$6$'.encode('utf8')+binascii.hexlify(key)
  54. f.write(hpk.decode('utf-8'))
  55. f.close()
  56. def get_digest_from_file(filename):
  57. """
  58. Read a digested password and salt from the file
  59. """
  60. f = open(filename, 'rt')
  61. salt, digest = f.readline().split('$6$')
  62. return salt.encode('utf-8'), digest.encode('utf-8')
  63. def get_cipher(password, salt):
  64. """
  65. Create a chiper object from a hashed password
  66. """
  67. iv = os.urandom(AES.block_size)
  68. dig = get_digest(password, salt)
  69. chiper = AES.new(dig, AES.MODE_ECB, iv)
  70. return chiper
  71. def cli_auth(reader=raw_input):
  72. """
  73. Read password from the user, if the password is correct,
  74. finish the execution an return the password and salt which
  75. are read from the file.
  76. """
  77. salt, digest = get_digest_from_file('passwords.txt')
  78. while True:
  79. password = reader("Please type in your password:").encode('utf-8')
  80. if authenticate(password, salt, digest):
  81. return password, salt
  82. def prepare_data(text, block_size):
  83. """
  84. prepare data before encryption so the lenght matches the expected
  85. lenght by the algorithm.
  86. """
  87. num_blocks = len(text)//block_size + 1
  88. newdatasize = block_size*num_blocks
  89. return text.ljust(newdatasize)
  90. def save_a_secret_message(reader=raw_input):
  91. """
  92. PoC to show we can encrypt a message
  93. """
  94. secret_msg = """This is a very important message! Learn Cryptography!!!"""
  95. # the secret message will be encrypted with the secret password found
  96. # in the file
  97. passwd, salt = cli_auth(reader=reader)
  98. cipher = get_cipher(passwd, salt)
  99. # explictly destroy password, so now there is no clear text reference
  100. # to the input given by the user
  101. del(passwd)
  102. msg = EncodeAES(cipher, prepare_data(secret_msg, AES.block_size))
  103. with open('secret.enc', 'wt') as s:
  104. s.write(msg.decode())
  105. print("The cipher message is:", msg.decode())
  106. def read_a_secret_message(reader=raw_input):
  107. """
  108. PoC to show we can decrypt a message
  109. """
  110. passwd, salt = cli_auth(reader)
  111. cipher = get_cipher(passwd, salt)
  112. del(passwd)
  113. with open('secret.enc') as s:
  114. msg = s.readline()
  115. print("The decrypted secret message is:")
  116. decoded = DecodeAES(cipher, msg)
  117. print(decoded)
  118. class CryptoEngine(object): # pagma: no cover
  119. _timeoutcount = 0
  120. _instance = None
  121. _instance_new = None
  122. _callback = None
  123. @classmethod
  124. def get(cls, dbver=0.5):
  125. if CryptoEngine._instance:
  126. return CryptoEngine._instance
  127. if CryptoEngine._instance_new:
  128. return CryptoEngine._instance_new
  129. keycrypted = config.get_value("Encryption", "keycrypted")
  130. algo = config.get_value("Encryption", "algorithm")
  131. if not algo:
  132. raise Exception("Parameters missing, no algorithm given")
  133. try:
  134. timeout = int(config.get_value("Encryption", "timeout"))
  135. except ValueError:
  136. timeout = -1
  137. salt, digest = get_digest_from_file('passwords.txt')
  138. kwargs = {'algorithm': algo,
  139. 'timeout': timeout, 'salt': salt, 'digest': digest}
  140. if dbver >= 0.5:
  141. CryptoEngine._instance_new = CryptoEngine(**kwargs)
  142. return CryptoEngine._instance_new
  143. def __init__(self, salt=None, digest=None, algorithm='AES',
  144. timeout=-1):
  145. """
  146. Initialise the Cryptographic Engine
  147. """
  148. self._algo = algorithm
  149. self._digest = digest if digest else None
  150. self._salt = salt if salt else None
  151. self._timeout = timeout
  152. self._cipher = None
  153. def authenticate(self, password):
  154. """
  155. salt and digest are stored in a file or a database
  156. """
  157. dig = get_digest(password, self._salt)
  158. return binascii.hexlify(dig) == self._digest
  159. def changepassword(self, reader=raw_input):
  160. self._keycrypted = self._create_password(reader=reader)
  161. return self._keycrypted
  162. @property
  163. def callback(self):
  164. """
  165. return call back function
  166. """
  167. return self._callback
  168. @callback.setter
  169. def callback(self, callback):
  170. if isinstance(callback, Callback):
  171. self._callback = callback
  172. self._getsecret = callback.getsecret
  173. self._getnewsecret = callback.getnewsecret
  174. else:
  175. raise Exception("callback must be an instance of Callback!")
  176. def _create_password(self, reader=raw_input):
  177. """
  178. Create a secret password as a hash and the salt used for this hash.
  179. Change reader to manipulate how input is given.
  180. """
  181. salt = base64.b64encode(os.urandom(32))
  182. passwd = reader("Please type in the secret key:")
  183. key = self._get_digest(passwd, salt)
  184. hpk = salt+'$6$'.encode('utf8')+binascii.hexlify(key)
  185. return hpk.decode('utf-8')
  186. def _get_digest(self, password, salt):
  187. """
  188. Get a digest based on clear text password
  189. """
  190. iterations = 5000
  191. return PBKDF2(password, salt, dkLen=32, count=iterations)
  192. if __name__ == '__main__': # pragma: no cover
  193. if '-i' in sys.argv:
  194. write_password()
  195. save_a_secret_message()
  196. read_a_secret_message()