filecrypt.py 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #!/usr/bin/env python3
  2. #
  3. # mmgen = Multi-Mode GENerator, command-line Bitcoin cold storage solution
  4. # Copyright (C)2013-2022 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. tool/filecrypt.py: File encryption/decryption routines for the 'mmgen-tool' utility
  20. """
  21. import os
  22. from .common import tool_cmd_base
  23. from ..crypto import mmgen_encrypt,mmgen_decrypt,mmenc_ext
  24. from ..fileutil import get_data_from_file,write_data_to_file
  25. class tool_cmd(tool_cmd_base):
  26. """
  27. file encryption and decryption
  28. MMGen encryption suite:
  29. * Key: Scrypt (user-configurable hash parameters, 32-byte salt)
  30. * Enc: AES256_CTR, 16-byte rand IV, sha256 hash + 32-byte nonce + data
  31. * The encrypted file is indistinguishable from random data
  32. """
  33. def encrypt(self,infile:str,outfile='',hash_preset=''):
  34. "encrypt a file"
  35. data = get_data_from_file( infile, 'data for encryption', binary=True )
  36. enc_d = mmgen_encrypt( data, 'data', hash_preset )
  37. if not outfile:
  38. outfile = f'{os.path.basename(infile)}.{mmenc_ext}'
  39. write_data_to_file( outfile, enc_d, 'encrypted data', binary=True )
  40. return True
  41. def decrypt(self,infile:str,outfile='',hash_preset=''):
  42. "decrypt a file"
  43. enc_d = get_data_from_file( infile, 'encrypted data', binary=True )
  44. while True:
  45. dec_d = mmgen_decrypt( enc_d, 'data', hash_preset )
  46. if dec_d:
  47. break
  48. msg('Trying again...')
  49. if not outfile:
  50. from ..util import remove_extension
  51. o = os.path.basename(infile)
  52. outfile = remove_extension(o,mmenc_ext)
  53. if outfile == o:
  54. outfile += '.dec'
  55. write_data_to_file( outfile, dec_d, 'decrypted data', binary=True )
  56. return True