Python скрыть часть кода

Saved searches

Use saved searches to filter your results more quickly

You signed in with another tab or window. Reload to refresh your session. You signed out in another tab or window. Reload to refresh your session. You switched accounts on another tab or window. Reload to refresh your session.

Transform regular Python code into a human-averse, yet still-functional equivalent.

License

brandonasuncion/Python-Code-Obfuscator

This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Name already in use

A tag already exists with the provided branch name. Many Git commands accept both tag and branch names, so creating this branch may cause unexpected behavior. Are you sure you want to create this branch?

Sign In Required

Please sign in to use Codespaces.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching GitHub Desktop

If nothing happens, download GitHub Desktop and try again.

Launching Xcode

If nothing happens, download Xcode and try again.

Launching Visual Studio Code

Your codespace will open once ready.

There was a problem preparing your codespace, please try again.

Latest commit

Git stats

Files

Failed to load latest commit information.

README.md

I was browsing /r/dailyprogrammer on Reddit one day, and attempted one of the daily challenges. After doing the challenge, I read through the comments and found a very interesting submission.

Seeing that baffled me at first sight, but after reading /u/ntxhhf’s breakdown of his code, I was inspired to make my own code obfuscator for Python using the ideas in his post.

What exactly does this script do?
It takes your regular-looking Python code, and obfuscates it! It takes any specified Python script, and will attempt to create an equivalent script that has the same exact functionality as the original, but is incredibly difficult for humans to read regularly.

So. how is this useful?
According to Wikipedia.

Programmers may deliberately obfuscate code to conceal its purpose (security through obscurity) or its logic or implicit values embedded in it, primarily, in order to prevent tampering, deter reverse engineering, or even as a puzzle or recreational challenge for someone reading the source code.

Input: Using Netwon’s Method to find the square root of 17

n = 17; x = 1 for i in range(100): x = x - ((x**2 - n) / (2*x)) print(x)
__=((()==[])+(()==[]));___=(__**__);____=((______));_____=((____(__**__)));______=((_____(__**__))); _________=((________));__________=((((________))(__**__)));_=((__**__)+(______(__**__)));_______=(__**__) for ________ in range((_____+(_________(__**__))+(__________(__**__)))): _______=_______-((_______**((______))-_)/(((______))*_______)) print(_______)

There are two ways the parser can encrypt strings. The first way is with hex strings, and the other using the number encoding method above.

Example Input: print(«Hello World!»)

_=((()==[])+(()==[]));__=(_**_);___=((____));____=((___(_**_)));_____=((______));______=((_____(_**_))); _______=str(''.join(chr(__RSV) for __RSV in [((____(_**_))+(______(_**_))),((_**_)+____+______+(((_____(_**_)))(_**_))), (____+(((___(_**_)))(_**_))+______+(((_____(_**_)))(_**_))),(____+(((___(_**_)))(_**_))+______+(((_____(_**_)))(_**_))), ((_**_)+___+____+(((___(_**_)))(_**_))+______+(((_____(_**_)))(_**_))),((_____(_**_))),((_**_)+___+____+_____+(((_____(_**_)))(_**_))), ((_**_)+___+____+(((___(_**_)))(_**_))+______+(((_____(_**_)))(_**_))),(___+_____+______+(((_____(_**_)))(_**_))), (____+(((___(_**_)))(_**_))+______+(((_____(_**_)))(_**_))),(____+______+(((_____(_**_)))(_**_))),((_**_)+______)])) print(_______)

Hiding Calls to Python’s Built-In Functions

In Python, we can call a built-in function indirectly: getattr(__import__(‘builtins’), ‘abs’)(5)
So to call a function, we just use the string-encoding method detailed above. It’s definitely not space-efficient, but it works!

Input: print(chr(65))

_=((()==[])+(()==[]));__=(_**_);___=((____));____=((___(_**_))); _____=((____(_**_)));______=((_____(_**_)));_______=((((_____(_**_)))(_**_))); ________=str(''.join(chr(__RSV) for __RSV in [((____)+(______(_**_))+(_______(_**_))), ((_**_)+____+______+_______+(((((_____(_**_)))(_**_)))(_**_))), ((_**_)+_____+_______+(((((_____(_**_)))(_**_)))(_**_))),(____+_____+_______+(((((_____(_**_)))(_**_)))(_**_))), (____+______+_______+(((((_____(_**_)))(_**_)))(_**_))),((_**_)+_____+_______+(((((_____(_**_)))(_**_)))(_**_))), (___+____+_____+_______+(((((_____(_**_)))(_**_)))(_**_))),((_**_)+___+______+_______+(((((_____(_**_)))(_**_)))(_**_)))])); _________=str(''.join(chr(__RSV) for __RSV in [(______+_______+(((((_____(_**_)))(_**_)))(_**_))), (___+______+_______+(((((_____(_**_)))(_**_)))(_**_))),((_**_)+_____+_______+(((((_____(_**_)))(_**_)))(_**_))), (___+____+_____+_______+(((((_____(_**_)))(_**_)))(_**_))),(____+______+_______+(((((_____(_**_)))(_**_)))(_**_)))])); __________=str(''.join(chr(__RSV) for __RSV in [((_**_)+___+_______+(((((_____(_**_)))(_**_)))(_**_))), (_____+_______+(((((_____(_**_)))(_**_)))(_**_))),(___+______+_______+(((((_____(_**_)))(_**_)))(_**_)))])) getattr(__import__(________), _________)(getattr(__import__(________), __________)(((_**_)+(((((_____(_**_)))(_**_)))(_**_)))))
usage: obfuscator.py [-h] [--debug] inputfile outputfile positional arguments: inputfile Name of the input file outputfile Name of the output file optional arguments: -h, --help show this help message and exit --debug Show debug info 
  • Should I use this for distributing my source code?
    As of the time I’m writing this, I highly recommend against that idea. There are some instances of code in that the parser cannot handle (multi-line strings, for instance). Also, the output really won’t do much to prevent reverse-engineering.
  • The output is too big! How do I reduce the output size?
    As of right now, the biggest impact is the inefficiency of encoding strings. For the smallest output, make sure to set the following constants in the script:
USE_HEXSTRINGS = True OBFUSCATE_BUILTINS = False REMOVE_COMMENTS = True 
  • Brandon Asuncion — Code
    Questions/Comments? Feel free to contact me at: me@brandonasuncion.tech
  • /u/ntxhhf — For the idea, and his breakdown of using lists/sets to create boolean values and integers

About

Transform regular Python code into a human-averse, yet still-functional equivalent.

Источник

PyArmor: как запутать код, чтобы защитить программное обеспечение

Все еще не шифруете свой скрипт? Тогда самое время изучить обфускацию. Сегодня познакомлю с полезной библиотекой PyArmor, расскажу о двух методах работы модуля и на собственном примере покажу, как запутать код от нежелательного просмотра третьими лицами.

В повседневной работе существуют ситуации, когда по очевидным причинам необходимо предоставить скрипты заказчику, но, пересылая собственные разработки, в полном объеме можно потерять контроль над ними, включая авторские права на реализованные коды.

В таких случаях целесообразно защитить собственные коды, зашифровав их (защитить/сохранить/добавить условия для управления зависимостями внутри кода), точно также, как если бы стояла задача предоставления кода для пользования клиенту в течение какого-либо определенного периода времени.

Разработчики скриптов знают, что код на Python поддерживает анализ байт-кода, позволяющий ускорять работу интерпретатора и сам код на Python очень сложно защитить от нежелательного просмотра третьими лицами. Даже новички в разработке скриптов на Python могут заполучить исходный скрипт .py из файла .exe.

Для этого случая на Python существует очень полезная библиотека pyarmor с помощью которой можно воспользоваться всеми вышеизложенными функциями защиты скрипта от нежелательного взлома и метод, который позволяет защитить код называется обфускация.

Библиотека PyArmor имеет несколько вариантов работы – через консоль, а также с использованием localhost GUI – графического пользовательского интерфейса.

Установка и использование библиотеки pyarmor

В консоли необходимо выполнить следующую команду, чтобы установить модуль:

Для того чтобы начать работу с графическим интерфейсом библиотеки необходимо сперва его установить, выполнив следующую команду:

Библиотеки успешно установлены, теперь можно приступить непосредственно к самому шифрованию скрипта.

В первую очередь необходимо создать отдельную папку, в которой будет храниться скрипт с кодом «my_script.py».

В качестве примера скрипта возьму самый простейший скрипт с математическими функциями и с определением функции вывода (функция вывода довольно проста и не нуждается в каких-либо пояснениях):

def math_primer1(x, y): return x + y * x * y def math_primer2(x, y): return x * y ** (x + y) if __name__ == «__main__»: result1 = math_primer2(2, 3) result2 = math_primer1(1, 2) print(result1, result2)

Теперь зашифрую этот код, выполнив в консоли несколько команд.

Для начала необходимо изменить путь до директории в которой лежит файл через:

Затем необходимо выполнить команду обфускации:

Источник

Читайте также:  Java work with big files
Оцените статью