kingspp
kingspp

Reputation: 311

Obfuscate a Python script in Unicode escape sequences

I want to obfuscate a Python script by using Unicode escape sequences.

For example,

print("Hello World")

in Unicode escape sequences is:

\x70\x72\x69\x6e\x74\x28\x22\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x22\x29

From my command line, I can achieve this with:

$ python3 -c \x70\x72\x69\x6e\x74\x28\x22\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x22\x29
Hello World

I've create a file and put the "Hello World" Unicode escape sequence in it as the source code.

But when I run it, I get:

$ python3 sample.py
SyntaxError: unexpected character after line continuation character

How can I use Unicode escape sequences in my source code.

Upvotes: 1

Views: 1525

Answers (1)

Alastair McCormack
Alastair McCormack

Reputation: 27724

You can use a PEP 263 header, which tells Python which encoding the source code is written in.

The format is:

# coding=<encoding name>

By using the unicode_escape codec (selected from https://docs.python.org/3/library/codecs.html), Python will unescape your strings first.

sample.py

# coding=unicode_escape
\x70\x72\x69\x6e\x74\x28\x22\x48\x65\x6c\x6c\x6f\x20\x57\x6f\x72\x6c\x64\x22\x29

Result:

$ python3 sample.py
Hello World

Upvotes: 2

Related Questions