crypto.py 7.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2019 The MMGen Project <mmgen@tuta.io>
  5. #
  6. # This program is free software: you can redistribute it and/or modify
  7. # it under the terms of the GNU General Public License as published by
  8. # the Free Software Foundation, either version 3 of the License, or
  9. # (at your option) any later version.
  10. #
  11. # This program is distributed in the hope that it will be useful,
  12. # but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. # GNU General Public License for more details.
  15. #
  16. # You should have received a copy of the GNU General Public License
  17. # along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. """
  19. crypto.py: Cryptographic and related routines for the MMGen suite
  20. """
  21. from cryptography.hazmat.primitives.ciphers import Cipher,algorithms,modes
  22. from cryptography.hazmat.backends import default_backend
  23. from hashlib import sha256
  24. from mmgen.common import *
  25. crmsg = {
  26. 'usr_rand_notice': """
  27. Since we don't fully trust our OS's random number generator, we'll provide
  28. some additional entropy of our own. Please type {} symbols on your keyboard.
  29. Type slowly and choose your symbols carefully for maximum randomness. Try to
  30. use both upper and lowercase as well as punctuation and numerals. What you
  31. type will not be displayed on the screen. Note that the timings between your
  32. keystrokes will also be used as a source of randomness.
  33. """
  34. }
  35. def sha256_rounds(s,n):
  36. for i in range(n):
  37. s = sha256(s).digest()
  38. return s
  39. def scramble_seed(seed,scramble_key):
  40. import hmac
  41. step1 = hmac.new(seed,scramble_key,sha256).digest()
  42. if g.debug:
  43. fs = 'Seed: {!r}\nScramble key: {}\nScrambled seed: {}\n'
  44. msg(fs.format(seed.hex(),scramble_key,step1.hex()))
  45. return sha256_rounds(step1,g.scramble_hash_rounds)
  46. def encrypt_seed(seed,key):
  47. return encrypt_data(seed,key,desc='seed')
  48. def decrypt_seed(enc_seed,key,seed_id,key_id):
  49. vmsg_r('Checking key...')
  50. chk1 = make_chksum_8(key)
  51. if key_id:
  52. if not compare_chksums(key_id,'key ID',chk1,'computed'):
  53. msg('Incorrect passphrase or hash preset')
  54. return False
  55. dec_seed = decrypt_data(enc_seed,key,desc='seed')
  56. chk2 = make_chksum_8(dec_seed)
  57. if seed_id:
  58. if compare_chksums(seed_id,'Seed ID',chk2,'decrypted seed'):
  59. qmsg('Passphrase is OK')
  60. else:
  61. if not opt.debug:
  62. msg_r('Checking key ID...')
  63. if compare_chksums(key_id,'key ID',chk1,'computed'):
  64. msg('Key ID is correct but decryption of seed failed')
  65. else:
  66. msg('Incorrect passphrase or hash preset')
  67. vmsg('')
  68. return False
  69. # else:
  70. # qmsg('Generated IDs (Seed/Key): {}/{}'.format(chk2,chk1))
  71. dmsg('Decrypted seed: {}'.format(dec_seed.hex()))
  72. return dec_seed
  73. def encrypt_data(data,key,iv=g.aesctr_dfl_iv,desc='data',verify=True):
  74. vmsg('Encrypting {}'.format(desc))
  75. c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
  76. encryptor = c.encryptor()
  77. enc_data = encryptor.update(data) + encryptor.finalize()
  78. if verify:
  79. vmsg_r('Performing a test decryption of the {}...'.format(desc))
  80. c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
  81. encryptor = c.encryptor()
  82. dec_data = encryptor.update(enc_data) + encryptor.finalize()
  83. if dec_data != data:
  84. die(2,"ERROR.\nDecrypted {s} doesn't match original {s}".format(s=desc))
  85. vmsg('done')
  86. return enc_data
  87. def decrypt_data(enc_data,key,iv=g.aesctr_dfl_iv,desc='data'):
  88. vmsg_r('Decrypting {} with key...'.format(desc))
  89. c = Cipher(algorithms.AES(key),modes.CTR(iv),backend=default_backend())
  90. encryptor = c.encryptor()
  91. return encryptor.update(enc_data) + encryptor.finalize()
  92. def scrypt_hash_passphrase(passwd,salt,hash_preset,buflen=32):
  93. # Buflen arg is for brainwallets only, which use this function to generate
  94. # the seed directly.
  95. N,r,p = get_hash_params(hash_preset)
  96. if type(passwd) == str: passwd = passwd.encode()
  97. def do_hashlib_scrypt():
  98. from hashlib import scrypt # Python >= v3.6
  99. return scrypt(passwd,salt=salt,n=2**N,r=r,p=p,maxmem=0,dklen=buflen)
  100. def do_standalone_scrypt():
  101. import scrypt
  102. return scrypt.hash(passwd,salt,2**N,r,p,buflen=buflen)
  103. msg_r('Hashing passphrase...')
  104. # hashlib.scrypt doesn't support N > 14 (hash preset 3)
  105. if N > 14 or g.force_standalone_scrypt_module:
  106. ret = do_standalone_scrypt()
  107. else:
  108. try: ret = do_hashlib_scrypt()
  109. except: ret = do_standalone_scrypt()
  110. msg('done')
  111. return ret
  112. def make_key(passwd,salt,hash_preset,desc='encryption key',from_what='passphrase',verbose=False):
  113. if from_what: desc += ' from '
  114. if opt.verbose or verbose:
  115. msg_r('Generating {}{}...'.format(desc,from_what))
  116. key = scrypt_hash_passphrase(passwd,salt,hash_preset)
  117. if opt.verbose or verbose: msg('done')
  118. dmsg('Key: {}'.format(key.hex()))
  119. return key
  120. def _get_random_data_from_user(uchars):
  121. m = 'Enter {} random symbols' if opt.quiet else crmsg['usr_rand_notice']
  122. msg(m.format(uchars))
  123. prompt = 'You may begin typing. {} symbols left: '
  124. import time
  125. from mmgen.term import get_char_raw
  126. key_data,time_data = bytes(),[]
  127. for i in range(uchars):
  128. key_data += get_char_raw('\r'+prompt.format(uchars-i))
  129. time_data.append(time.time())
  130. if opt.quiet: msg_r('\r')
  131. else: msg_r("\rThank you. That's enough.{}\n\n".format(' '*18))
  132. fmt_time_data = list(map('{:.22f}'.format,time_data))
  133. dmsg('\nUser input:\n{!r}\nKeystroke time values:\n{}\n'.format(key_data,'\n'.join(fmt_time_data)))
  134. prompt = 'User random data successfully acquired. Press ENTER to continue'
  135. prompt_and_get_char(prompt,'',enter_ok=True)
  136. return key_data+''.join(fmt_time_data).encode()
  137. def get_random(length):
  138. os_rand = os.urandom(length)
  139. if opt.usr_randchars:
  140. from_what = 'OS random data'
  141. if not g.user_entropy:
  142. g.user_entropy = \
  143. sha256(_get_random_data_from_user(opt.usr_randchars)).digest()
  144. from_what += ' plus user-supplied entropy'
  145. else:
  146. from_what += ' plus saved user-supplied entropy'
  147. key = make_key(g.user_entropy,b'','2',from_what=from_what,verbose=True)
  148. return encrypt_data(os_rand,key,desc='random data',verify=False)
  149. else:
  150. return os_rand
  151. def get_hash_preset_from_user(hp=g.hash_preset,desc='data'):
  152. prompt = """Enter hash preset for {},
  153. or hit ENTER to accept the default value ('{}'): """.format(desc,hp)
  154. while True:
  155. ret = my_raw_input(prompt)
  156. if ret:
  157. if ret in g.hash_presets.keys():
  158. return ret
  159. else:
  160. m = 'Invalid input. Valid choices are {}'
  161. msg(m.format(', '.join(sorted(g.hash_presets.keys()))))
  162. continue
  163. else: return hp
  164. _salt_len,_sha256_len,_nonce_len = 32,32,32
  165. def mmgen_encrypt(data,desc='data',hash_preset=''):
  166. salt = get_random(_salt_len)
  167. iv = get_random(g.aesctr_iv_len)
  168. nonce = get_random(_nonce_len)
  169. hp = hash_preset or (
  170. opt.hash_preset if 'hash_preset' in opt.set_by_user else get_hash_preset_from_user('3',desc))
  171. m = ('user-requested','default')[hp=='3']
  172. vmsg('Encrypting {}'.format(desc))
  173. qmsg("Using {} hash preset of '{}'".format(m,hp))
  174. passwd = get_new_passphrase(desc,{})
  175. key = make_key(passwd,salt,hp)
  176. enc_d = encrypt_data(sha256(nonce+data).digest() + nonce + data, key, iv, desc=desc)
  177. return salt+iv+enc_d
  178. def mmgen_decrypt(data,desc='data',hash_preset=''):
  179. vmsg('Preparing to decrypt {}'.format(desc))
  180. dstart = _salt_len + g.aesctr_iv_len
  181. salt = data[:_salt_len]
  182. iv = data[_salt_len:dstart]
  183. enc_d = data[dstart:]
  184. hp = hash_preset or (
  185. opt.hash_preset if 'hash_preset' in opt.set_by_user else get_hash_preset_from_user('3',desc))
  186. m = ('user-requested','default')[hp=='3']
  187. qmsg("Using {} hash preset of '{}'".format(m,hp))
  188. passwd = get_mmgen_passphrase(desc)
  189. key = make_key(passwd,salt,hp)
  190. dec_d = decrypt_data(enc_d,key,iv,desc)
  191. if dec_d[:_sha256_len] == sha256(dec_d[_sha256_len:]).digest():
  192. vmsg('OK')
  193. return dec_d[_sha256_len+_nonce_len:]
  194. else:
  195. msg('Incorrect passphrase or hash preset')
  196. return False
  197. def mmgen_decrypt_retry(d,desc='data'):
  198. while True:
  199. d_dec = mmgen_decrypt(d,desc)
  200. if d_dec: return d_dec
  201. msg('Trying again...')