I haven't spent along time on this (it could be improved), this is my first time using the tokenize module, but here's what I came up with.
As I was looking for a python parser I found this module, it basically parses python code and categorizes it, from there you can do what you want with it.
from token import DEDENT, INDENT, NEWLINE
import tokenize
result = ''
names = {
'if': 'hehe',
'elif': 'haha',
'else': 'hihi',
# Add here all the other names, that you want to change, and don't worry about a name occurring inside a string it will not be changed
}
# open the script you want to encrypt in a tokenize file object
with tokenize.open('z.py') as f:
# create a new tokenize object and feed it the lines
tokens = tokenize.generate_tokens(f.readline)
# for every token in all the tokens in the file:
for token in tokens:
if names.get(token[1]): # token[1] is the string of the token i.e 'if', 'for', '\n', 'or' etc
result += names.get(token[1]) + ' '
elif token.type == NEWLINE or token[1] == INDENT or token.type == DEDENT:
result += token[1]
print(result)
else:
result += token[1] + ' '
with open('z.py', 'w') as f:
f.write(result)
update
the previous code, only encodes, with some minor alterations, you can reuse the same code to decode and encode the script:
from token import DEDENT, INDENT, NEWLINE
import tokenize
encode_name = {
'if': 'hehe',
'elif': 'haha',
'else': 'hihi',
}
def code(name, encode=True):
if encode:
names = name
else:
# flip the dict, keys become values and vice versa
names = {v: k for k, v in name.items()}
result = ''
with tokenize.open('z.py') as f:
tokens = tokenize.generate_tokens(f.readline)
for token in tokens:
if names.get(token[1]):
result += names.get(token[1]) + ' '
elif token.type == NEWLINE or token[1] == INDENT or token.type == DEDENT:
result += token[1]
else:
result += token[1] + ' '
with open('z.py', 'w') as f:
f.write(result)
code(encode_name, encode = False)
check out the official docs for more information i am no expert my self but don't hesitate to ask anything here.
very happy to help
good luck, happy coding