crypto.py 6.6 KB

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