crypto.py 6.7 KB

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