



"""simple docstring"""







import os
import sys

from . import rsa_key_generator as rkg

UpperCAmelCase:  int			     =				128
UpperCAmelCase:  Dict			     =				256


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE      ):
		_lowercase				: Any     =   message.encode("""ascii"""      )

		_lowercase				: Dict     =   []
		for block_start in range(0   ,				len(__UpperCAmelCase      )   ,				__UpperCAmelCase      ):
				_lowercase				: int     =   0
				for i in range(__UpperCAmelCase   ,				min(block_start + block_size   ,				len(__UpperCAmelCase      )      )      ):
						block_int += message_bytes[i] * (BYTE_SIZE ** (i % block_size))
				block_ints.append(__UpperCAmelCase      )
		return block_ints


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE      ):
		_lowercase				: list[str]     =   []
		for block_int in block_ints:
				_lowercase				: list[str]     =   []
				for i in range(block_size - 1   ,				-1   ,				-1      ):
						if len(__UpperCAmelCase      ) + i < message_length:
								_lowercase				: Optional[int]     =   block_int // (BYTE_SIZE**i)
								_lowercase				: List[Any]     =   block_int % (BYTE_SIZE**i)
								block_message.insert(0   ,				chr(__UpperCAmelCase      )      )
				message.extend(__UpperCAmelCase      )
		return "".join(__UpperCAmelCase      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE      ):
		_lowercase				: int     =   []
		_lowercase     ,  _lowercase				: List[Any]     =   key

		for block in get_blocks_from_text(__UpperCAmelCase   ,				__UpperCAmelCase      ):
				encrypted_blocks.append(pow(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )      )
		return encrypted_blocks


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE   ,				):
		_lowercase				: Tuple     =   []
		_lowercase     ,  _lowercase				: Optional[int]     =   key
		for block in encrypted_blocks:
				decrypted_blocks.append(pow(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )      )
		return get_text_from_blocks(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase      ):
		with open(__UpperCAmelCase      ) as fo:
				_lowercase				: Optional[Any]     =   fo.read()
		_lowercase     ,  _lowercase     ,  _lowercase				: Optional[Any]     =   content.split(""","""      )
		return (int(__UpperCAmelCase      ), int(__UpperCAmelCase      ), int(__UpperCAmelCase      ))


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase = DEFAULT_BLOCK_SIZE   ,				):
		_lowercase     ,  _lowercase     ,  _lowercase				: Optional[Any]     =   read_key_file(__UpperCAmelCase      )
		if key_size < block_size * 8:
				sys.exit(
				    """ERROR: Block size is {} bits and key size is {} bits. The RSA cipher """
				    """requires the block size to be equal to or greater than the key size. """
				    """Either decrease the block size or use different keys.""".format(
				        block_size * 8   ,				__UpperCAmelCase      )      )

		_lowercase				: str     =   [str(__UpperCAmelCase      ) for i in encrypt_message(__UpperCAmelCase   ,				(n, e)   ,				__UpperCAmelCase      )]

		_lowercase				: List[str]     =   """,""".join(__UpperCAmelCase      )
		_lowercase				: List[Any]     =   F"""{len(__UpperCAmelCase      )}_{block_size}_{encrypted_content}"""
		with open(__UpperCAmelCase   ,				"""w"""      ) as fo:
				fo.write(__UpperCAmelCase      )
		return encrypted_content


def  __SCREAMING_SNAKE_CASE (  __UpperCAmelCase   ,				__UpperCAmelCase      ):
		_lowercase     ,  _lowercase     ,  _lowercase				: List[Any]     =   read_key_file(__UpperCAmelCase      )
		with open(__UpperCAmelCase      ) as fo:
				_lowercase				: List[Any]     =   fo.read()
		_lowercase     ,  _lowercase     ,  _lowercase				: int     =   content.split("""_"""      )
		_lowercase				: Union[str, Any]     =   int(__UpperCAmelCase      )
		_lowercase				: Union[str, Any]     =   int(__UpperCAmelCase      )

		if key_size < block_size * 8:
				sys.exit(
				    """ERROR: Block size is {} bits and key size is {} bits. The RSA cipher """
				    """requires the block size to be equal to or greater than the key size. """
				    """Did you specify the correct key file and encrypted file?""".format(
				        block_size * 8   ,				__UpperCAmelCase      )      )

		_lowercase				: Any     =   []
		for block in encrypted_message.split(""","""      ):
				encrypted_blocks.append(int(__UpperCAmelCase      )      )

		return decrypt_message(__UpperCAmelCase   ,				__UpperCAmelCase   ,				(n, d)   ,				__UpperCAmelCase      )


def  __SCREAMING_SNAKE_CASE (  ):
		_lowercase				: Optional[int]     =   """encrypted_file.txt"""
		_lowercase				: Tuple     =   input(R"""Encrypt\Decrypt [e\d]: """      )

		if response.lower().startswith("""e"""      ):
				_lowercase				: Union[str, Any]     =   """encrypt"""
		elif response.lower().startswith("""d"""      ):
				_lowercase				: Any     =   """decrypt"""

		if mode == "encrypt":
				if not os.path.exists("""rsa_pubkey.txt"""      ):
						rkg.make_key_files("""rsa"""   ,				1024      )

				_lowercase				: Optional[int]     =   input("""\nEnter message: """      )
				_lowercase				: Any     =   """rsa_pubkey.txt"""
				print(F"""Encrypting and writing to {filename}..."""      )
				_lowercase				: Optional[int]     =   encrypt_and_write_to_file(__UpperCAmelCase   ,				__UpperCAmelCase   ,				__UpperCAmelCase      )

				print("""\nEncrypted text:"""      )
				print(__UpperCAmelCase      )

		elif mode == "decrypt":
				_lowercase				: Any     =   """rsa_privkey.txt"""
				print(F"""Reading from {filename} and decrypting..."""      )
				_lowercase				: List[str]     =   read_from_file_and_decrypt(__UpperCAmelCase   ,				__UpperCAmelCase      )
				print("""writing decryption to rsa_decryption.txt..."""      )
				with open("""rsa_decryption.txt"""   ,				"""w"""      ) as dec:
						dec.write(__UpperCAmelCase      )

				print("""\nDecryption:"""      )
				print(__UpperCAmelCase      )


if __name__ == "__main__":
		main()





'''simple docstring'''







from typing import TYPE_CHECKING

from ..utils import OptionalDependencyNotAvailable, _LazyModule, is_flax_available, is_tf_available, is_torch_available


_lowercase					:    Tuple       				=			{
    "configuration_utils": ["GenerationConfig"],
    "streamers": ["TextIteratorStreamer", "TextStreamer"],
}

try:
							if not is_torch_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							_lowercase					:    List[Any]       				=			[
							    "Constraint",
							    "ConstraintListState",
							    "DisjunctiveConstraint",
							    "PhrasalConstraint",
							]
							_lowercase					:    int       				=			[
							    "BeamHypotheses",
							    "BeamScorer",
							    "BeamSearchScorer",
							    "ConstrainedBeamSearchScorer",
							]
							_lowercase					:    str       				=			[
							    "EpsilonLogitsWarper",
							    "EtaLogitsWarper",
							    "ForcedBOSTokenLogitsProcessor",
							    "ForcedEOSTokenLogitsProcessor",
							    "HammingDiversityLogitsProcessor",
							    "InfNanRemoveLogitsProcessor",
							    "LogitsProcessor",
							    "LogitsProcessorList",
							    "LogitsWarper",
							    "MinLengthLogitsProcessor",
							    "MinNewTokensLengthLogitsProcessor",
							    "NoBadWordsLogitsProcessor",
							    "NoRepeatNGramLogitsProcessor",
							    "PrefixConstrainedLogitsProcessor",
							    "RepetitionPenaltyLogitsProcessor",
							    "SequenceBiasLogitsProcessor",
							    "EncoderRepetitionPenaltyLogitsProcessor",
							    "TemperatureLogitsWarper",
							    "TopKLogitsWarper",
							    "TopPLogitsWarper",
							    "TypicalLogitsWarper",
							    "EncoderNoRepeatNGramLogitsProcessor",
							    "ExponentialDecayLengthPenalty",
							    "LogitNormalization",
							]
							_lowercase					:    int       				=			[
							    "MaxNewTokensCriteria",
							    "MaxLengthCriteria",
							    "MaxTimeCriteria",
							    "StoppingCriteria",
							    "StoppingCriteriaList",
							    "validate_stopping_criteria",
							]
							_lowercase					:    List[Any]       				=			[
							    "GenerationMixin",
							    "top_k_top_p_filtering",
							    "GreedySearchEncoderDecoderOutput",
							    "GreedySearchDecoderOnlyOutput",
							    "SampleEncoderDecoderOutput",
							    "SampleDecoderOnlyOutput",
							    "BeamSearchEncoderDecoderOutput",
							    "BeamSearchDecoderOnlyOutput",
							    "BeamSampleEncoderDecoderOutput",
							    "BeamSampleDecoderOnlyOutput",
							    "ContrastiveSearchEncoderDecoderOutput",
							    "ContrastiveSearchDecoderOnlyOutput",
							]

try:
							if not is_tf_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							_lowercase					:    Optional[Any]       				=			[
							    "TFForcedBOSTokenLogitsProcessor",
							    "TFForcedEOSTokenLogitsProcessor",
							    "TFLogitsProcessor",
							    "TFLogitsProcessorList",
							    "TFLogitsWarper",
							    "TFMinLengthLogitsProcessor",
							    "TFNoBadWordsLogitsProcessor",
							    "TFNoRepeatNGramLogitsProcessor",
							    "TFRepetitionPenaltyLogitsProcessor",
							    "TFTemperatureLogitsWarper",
							    "TFTopKLogitsWarper",
							    "TFTopPLogitsWarper",
							    "TFForceTokensLogitsProcessor",
							    "TFSuppressTokensAtBeginLogitsProcessor",
							    "TFSuppressTokensLogitsProcessor",
							]
							_lowercase					:    List[Any]       				=			[
							    "TFGenerationMixin",
							    "tf_top_k_top_p_filtering",
							    "TFGreedySearchDecoderOnlyOutput",
							    "TFGreedySearchEncoderDecoderOutput",
							    "TFSampleEncoderDecoderOutput",
							    "TFSampleDecoderOnlyOutput",
							    "TFBeamSearchEncoderDecoderOutput",
							    "TFBeamSearchDecoderOnlyOutput",
							    "TFBeamSampleEncoderDecoderOutput",
							    "TFBeamSampleDecoderOnlyOutput",
							    "TFContrastiveSearchEncoderDecoderOutput",
							    "TFContrastiveSearchDecoderOnlyOutput",
							]

try:
							if not is_flax_available():
														raise OptionalDependencyNotAvailable()
except OptionalDependencyNotAvailable:
							pass
else:
							_lowercase					:    List[str]       				=			[
							    "FlaxForcedBOSTokenLogitsProcessor",
							    "FlaxForcedEOSTokenLogitsProcessor",
							    "FlaxLogitsProcessor",
							    "FlaxLogitsProcessorList",
							    "FlaxLogitsWarper",
							    "FlaxMinLengthLogitsProcessor",
							    "FlaxTemperatureLogitsWarper",
							    "FlaxTopKLogitsWarper",
							    "FlaxTopPLogitsWarper",
							]
							_lowercase					:    Optional[int]       				=			[
							    "FlaxGenerationMixin",
							    "FlaxGreedySearchOutput",
							    "FlaxSampleOutput",
							    "FlaxBeamSearchOutput",
							]

if TYPE_CHECKING:
							from .configuration_utils import GenerationConfig
							from .streamers import TextIteratorStreamer, TextStreamer

							try:
														if not is_torch_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .beam_constraints import Constraint, ConstraintListState, DisjunctiveConstraint, PhrasalConstraint
														from .beam_search import BeamHypotheses, BeamScorer, BeamSearchScorer, ConstrainedBeamSearchScorer
														from .logits_process import (
														    EncoderNoRepeatNGramLogitsProcessor,
														    EncoderRepetitionPenaltyLogitsProcessor,
														    EpsilonLogitsWarper,
														    EtaLogitsWarper,
														    ExponentialDecayLengthPenalty,
														    ForcedBOSTokenLogitsProcessor,
														    ForcedEOSTokenLogitsProcessor,
														    HammingDiversityLogitsProcessor,
														    InfNanRemoveLogitsProcessor,
														    LogitNormalization,
														    LogitsProcessor,
														    LogitsProcessorList,
														    LogitsWarper,
														    MinLengthLogitsProcessor,
														    MinNewTokensLengthLogitsProcessor,
														    NoBadWordsLogitsProcessor,
														    NoRepeatNGramLogitsProcessor,
														    PrefixConstrainedLogitsProcessor,
														    RepetitionPenaltyLogitsProcessor,
														    SequenceBiasLogitsProcessor,
														    TemperatureLogitsWarper,
														    TopKLogitsWarper,
														    TopPLogitsWarper,
														    TypicalLogitsWarper,
														)
														from .stopping_criteria import (
														    MaxLengthCriteria,
														    MaxNewTokensCriteria,
														    MaxTimeCriteria,
														    StoppingCriteria,
														    StoppingCriteriaList,
														    validate_stopping_criteria,
														)
														from .utils import (
														    BeamSampleDecoderOnlyOutput,
														    BeamSampleEncoderDecoderOutput,
														    BeamSearchDecoderOnlyOutput,
														    BeamSearchEncoderDecoderOutput,
														    ContrastiveSearchDecoderOnlyOutput,
														    ContrastiveSearchEncoderDecoderOutput,
														    GenerationMixin,
														    GreedySearchDecoderOnlyOutput,
														    GreedySearchEncoderDecoderOutput,
														    SampleDecoderOnlyOutput,
														    SampleEncoderDecoderOutput,
														    top_k_top_p_filtering,
														)

							try:
														if not is_tf_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .tf_logits_process import (
														    TFForcedBOSTokenLogitsProcessor,
														    TFForcedEOSTokenLogitsProcessor,
														    TFForceTokensLogitsProcessor,
														    TFLogitsProcessor,
														    TFLogitsProcessorList,
														    TFLogitsWarper,
														    TFMinLengthLogitsProcessor,
														    TFNoBadWordsLogitsProcessor,
														    TFNoRepeatNGramLogitsProcessor,
														    TFRepetitionPenaltyLogitsProcessor,
														    TFSuppressTokensAtBeginLogitsProcessor,
														    TFSuppressTokensLogitsProcessor,
														    TFTemperatureLogitsWarper,
														    TFTopKLogitsWarper,
														    TFTopPLogitsWarper,
														)
														from .tf_utils import (
														    TFBeamSampleDecoderOnlyOutput,
														    TFBeamSampleEncoderDecoderOutput,
														    TFBeamSearchDecoderOnlyOutput,
														    TFBeamSearchEncoderDecoderOutput,
														    TFContrastiveSearchDecoderOnlyOutput,
														    TFContrastiveSearchEncoderDecoderOutput,
														    TFGenerationMixin,
														    TFGreedySearchDecoderOnlyOutput,
														    TFGreedySearchEncoderDecoderOutput,
														    TFSampleDecoderOnlyOutput,
														    TFSampleEncoderDecoderOutput,
														    tf_top_k_top_p_filtering,
														)

							try:
														if not is_flax_available():
																					raise OptionalDependencyNotAvailable()
							except OptionalDependencyNotAvailable:
														pass
							else:
														from .flax_logits_process import (
														    FlaxForcedBOSTokenLogitsProcessor,
														    FlaxForcedEOSTokenLogitsProcessor,
														    FlaxLogitsProcessor,
														    FlaxLogitsProcessorList,
														    FlaxLogitsWarper,
														    FlaxMinLengthLogitsProcessor,
														    FlaxTemperatureLogitsWarper,
														    FlaxTopKLogitsWarper,
														    FlaxTopPLogitsWarper,
														)
														from .flax_utils import FlaxBeamSearchOutput, FlaxGenerationMixin, FlaxGreedySearchOutput, FlaxSampleOutput
else:
							import sys

							_lowercase					:    Tuple       				=			_LazyModule(__name__, globals()["__file__"], _import_structure, module_spec=__spec__)



