pyz_crypto.py 1.3 KB

123456789101112131415161718192021222324252627282930313233343536373839
  1. #-----------------------------------------------------------------------------
  2. # Copyright (c) 2005-2021, PyInstaller Development Team.
  3. #
  4. # Distributed under the terms of the GNU General Public License (version 2
  5. # or later) with exception for distributing the bootloader.
  6. #
  7. # The full license is in the file COPYING.txt, distributed with this software.
  8. #
  9. # SPDX-License-Identifier: (GPL-2.0-or-later WITH Bootloader-exception)
  10. #-----------------------------------------------------------------------------
  11. import os
  12. BLOCK_SIZE = 16
  13. class PyiBlockCipher(object):
  14. """
  15. This class is used only to encrypt Python modules.
  16. """
  17. def __init__(self, key=None):
  18. assert type(key) is str
  19. if len(key) > BLOCK_SIZE:
  20. self.key = key[0:BLOCK_SIZE]
  21. else:
  22. self.key = key.zfill(BLOCK_SIZE)
  23. assert len(self.key) == BLOCK_SIZE
  24. import tinyaes
  25. self._aesmod = tinyaes
  26. def encrypt(self, data):
  27. iv = os.urandom(BLOCK_SIZE)
  28. return iv + self.__create_cipher(iv).CTR_xcrypt_buffer(data)
  29. def __create_cipher(self, iv):
  30. # The 'AES' class is stateful, and this factory method is used to re-initialize the block cipher class with
  31. # each call to xcrypt().
  32. return self._aesmod.AES(self.key.encode(), iv)