crypto.py 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180
  1. from getpass import getpass
  2. import hashlib
  3. import os
  4. import logging
  5. import msgpack
  6. import zlib
  7. from pbkdf2 import pbkdf2
  8. from Crypto.Cipher import AES
  9. from Crypto.Hash import SHA256, HMAC
  10. from Crypto.PublicKey import RSA
  11. from Crypto.Util import Counter
  12. from Crypto.Util.number import bytes_to_long
  13. from .helpers import IntegrityError
  14. from .oaep import OAEP
  15. class KeyChain(object):
  16. def __init__(self, path=None):
  17. self.aes_id = self.rsa_read = self.rsa_create = None
  18. self.path = path
  19. if path:
  20. self.open(path)
  21. def open(self, path):
  22. with open(path, 'rb') as fd:
  23. cdata = fd.read()
  24. data = self.decrypt(cdata, '')
  25. while not data:
  26. self.password = getpass('Keychain password: ')
  27. if not self.password:
  28. raise Exception('Keychain decryption failed')
  29. data = self.decrypt(cdata, self.password)
  30. if not data:
  31. logging.error('Incorrect password')
  32. chain = msgpack.unpackb(data)
  33. logging.info('Key chain "%s" opened', path)
  34. assert chain['version'] == 1
  35. self.aes_id = chain['aes_id']
  36. self.rsa_read = RSA.importKey(chain['rsa_read'])
  37. self.rsa_create = RSA.importKey(chain['rsa_create'])
  38. def encrypt(self, data, password):
  39. salt = os.urandom(32)
  40. iterations = 2000
  41. key = pbkdf2(password, salt, 32, iterations, hashlib.sha256)
  42. hash = HMAC.new(key, data, SHA256).digest()
  43. cdata = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).encrypt(data)
  44. d = {
  45. 'version': 1,
  46. 'salt': salt,
  47. 'iterations': iterations,
  48. 'algorithm': 'SHA256',
  49. 'hash': hash,
  50. 'data': cdata,
  51. }
  52. return msgpack.packb(d)
  53. def decrypt(self, data, password):
  54. d = msgpack.unpackb(data)
  55. assert d['version'] == 1
  56. assert d['algorithm'] == 'SHA256'
  57. key = pbkdf2(password, d['salt'], 32, d['iterations'], hashlib.sha256)
  58. data = AES.new(key, AES.MODE_CTR, counter=Counter.new(128)).decrypt(d['data'])
  59. if HMAC.new(key, data, SHA256).digest() != d['hash']:
  60. return None
  61. return data
  62. def save(self, path, password):
  63. chain = {
  64. 'version': 1,
  65. 'aes_id': self.aes_id,
  66. 'rsa_read': self.rsa_read.exportKey('PEM'),
  67. 'rsa_create': self.rsa_create.exportKey('PEM'),
  68. }
  69. data = self.encrypt(msgpack.packb(chain), password)
  70. with open(path, 'wb') as fd:
  71. fd.write(data)
  72. logging.info('Key chain "%s" saved', path)
  73. def restrict(self, path):
  74. if os.path.exists(path):
  75. logging.error('%s already exists', path)
  76. return 1
  77. self.rsa_read = self.rsa_read.publickey()
  78. self.save(path, self.password)
  79. return 0
  80. def chpass(self):
  81. self.rsa_read = self.rsa_read.publickey()
  82. password, password2 = 1, 2
  83. while password != password2:
  84. password = getpass('New password: ')
  85. password2 = getpass('New password again: ')
  86. if password != password2:
  87. logging.error('Passwords do not match')
  88. self.save(self.path, password)
  89. return 0
  90. @staticmethod
  91. def generate(path):
  92. if os.path.exists(path):
  93. logging.error('%s already exists', path)
  94. return 1
  95. password, password2 = 1, 2
  96. while password != password2:
  97. password = getpass('Keychain password: ')
  98. password2 = getpass('Keychain password again: ')
  99. if password != password2:
  100. logging.error('Passwords do not match')
  101. chain = KeyChain()
  102. logging.info('Generating keys')
  103. chain.aes_id = os.urandom(32)
  104. chain.rsa_read = RSA.generate(2048)
  105. chain.rsa_create = RSA.generate(2048)
  106. chain.save(path, password)
  107. return 0
  108. class CryptoManager(object):
  109. CREATE = '\1'
  110. READ = '\2'
  111. def __init__(self, keychain):
  112. self._key_cache = {}
  113. self.keychain = keychain
  114. self.read_key = os.urandom(32)
  115. self.create_key = os.urandom(32)
  116. self.read_encrypted = OAEP(256, hash=SHA256).encode(self.read_key, os.urandom(32))
  117. self.read_encrypted = keychain.rsa_read.encrypt(self.read_encrypted, '')[0]
  118. self.create_encrypted = OAEP(256, hash=SHA256).encode(self.create_key, os.urandom(32))
  119. self.create_encrypted = keychain.rsa_create.encrypt(self.create_encrypted, '')[0]
  120. def id_hash(self, data):
  121. return HMAC.new(self.keychain.aes_id, data, SHA256).digest()
  122. def encrypt_read(self, data):
  123. data = zlib.compress(data)
  124. hash = self.id_hash(data)
  125. counter = Counter.new(128, initial_value=bytes_to_long(hash[:16]), allow_wraparound=True)
  126. data = AES.new(self.read_key, AES.MODE_CTR, '', counter=counter).encrypt(data)
  127. return ''.join((self.READ, self.read_encrypted, hash, data)), hash
  128. def encrypt_create(self, data):
  129. data = zlib.compress(data)
  130. hash = self.id_hash(data)
  131. counter = Counter.new(128, initial_value=bytes_to_long(hash[:16]), allow_wraparound=True)
  132. data = AES.new(self.create_key, AES.MODE_CTR, '', counter=counter).encrypt(data)
  133. return ''.join((self.CREATE, self.create_encrypted, hash, data)), hash
  134. def decrypt_key(self, data, rsa_key):
  135. try:
  136. return self._key_cache[data]
  137. except KeyError:
  138. self._key_cache[data] = OAEP(256, hash=SHA256).decode(rsa_key.decrypt(data))
  139. return self._key_cache[data]
  140. def decrypt(self, data):
  141. type = data[0]
  142. if type == self.READ:
  143. key = self.decrypt_key(data[1:257], self.keychain.rsa_read)
  144. hash = data[257:289]
  145. counter = Counter.new(128, initial_value=bytes_to_long(hash[:16]), allow_wraparound=True)
  146. data = AES.new(key, AES.MODE_CTR, counter=counter).decrypt(data[289:])
  147. if self.id_hash(data) != hash:
  148. raise IntegrityError('decryption failed')
  149. return zlib.decompress(data), hash
  150. elif type == self.CREATE:
  151. key = self.decrypt_key(data[1:257], self.keychain.rsa_create)
  152. hash = data[257:289]
  153. counter = Counter.new(128, initial_value=bytes_to_long(hash[:16]), allow_wraparound=True)
  154. data = AES.new(key, AES.MODE_CTR, '', counter=counter).decrypt(data[289:])
  155. if self.id_hash(data) != hash:
  156. raise IntegrityError('decryption failed')
  157. return zlib.decompress(data), hash
  158. else:
  159. raise Exception('Unknown pack type %d found' % ord(type))