用C加密/解密加密Python脚本

重复(我没有找到答案): https : //stackoverflow.com/questions/4066361/how-to-obfuscate-python-code 如何保护Python代码?

所以我查看了^^上面的两个链接,我发现没有什么用于实际加密python脚本和/或混淆python代码。 所以我是C的新手,但是在python中经验丰富,如果我想开发商业python项目,我最好的想法是:

创建ac脚本和加密和编译的python脚本 C脚本需要简单地提供字符串加密密钥并对其进行解密。 仅仅是因为我从未真正尝试加密,我知道这不会是完美的。 但我不需要完美。 我只是想让我的python源代码反编译更难,意识到这仍然很容易但不容易。

我目前看过Cython,我可以轻松生成一个* .c文件,现在如何将其编译为二进制文件? (与视觉工作室)

那么我怎样才能加密我的python代码并从C脚本解密它(我可以编译成二进制代码使其编辑起来更加困难)?

这就是我要做的事情:

1)创建一个C脚本,生成一个密钥并将其存储到文本文件中

2)拿起密钥并在运行Python时立即删除文本文件

3)使用密钥解密Python代码的真正重要部分(确保没有这些位将破坏您的脚本) 然后导入所有

4)立即重新加密重要的Python位,并删除.pyc文件

这将是可以击败的,但你没关系。

要加密和重新加密python位,请尝试以下代码:

 from hashlib import md5 from Crypto.Cipher import AES from Crypto import Random def encrypt(in_file, out_file, password, key_length=32): bs = AES.block_size salt = Random.new().read(bs - len('Salted__')) key, iv = derive_key_and_iv(password, salt, key_length, bs) cipher = AES.new(key, AES.MODE_CBC, iv) out_file.write('Salted__' + salt) finished = False while not finished: chunk = in_file.read(1024 * bs) if len(chunk) == 0 or len(chunk) % bs != 0: padding_length = (bs - len(chunk) % bs) or bs chunk += padding_length * chr(padding_length) finished = True out_file.write(cipher.encrypt(chunk)) def decrypt(in_file, out_file, password, key_length=32): bs = AES.block_size salt = in_file.read(bs)[len('Salted__'):] key, iv = derive_key_and_iv(password, salt, key_length, bs) cipher = AES.new(key, AES.MODE_CBC, iv) next_chunk = '' finished = False while not finished: chunk, next_chunk = next_chunk, cipher.decrypt(in_file.read(1024 * bs)) if len(next_chunk) == 0: padding_length = ord(chunk[-1]) chunk = chunk[:-padding_length] finished = True out_file.write(chunk) 

总结一下,这里有一些伪代码:

 def main(): os.system("C_Executable.exe") with open("key.txt",'r') as f: key = f.read() os.remove("key.txt") #Calls to decrpyt files which look like this: with open("Encrypted file name"), 'rb') as in_file, open("unecrypted file name"), 'wb') as out_file: decrypt(in_file, out_file, key) os.remove("encrypted file name") import fileA, fileB, fileC, etc global fileA, fileB, fileC, etc #Calls to re-encrypt files and remove unencrypted versions along with .pyc files using a similar scheme to decryption calls #Whatever else you want 

但只是强调和重点,

Python不是为此而制作的! 它意味着开放和自由!

如果你发现自己处于这个关键时刻没有其他选择,你可能应该使用不同的语言

看看Nuitka项目。 它是一个python编译器,可以将python脚本编译为使用libpython运行的本机可执行代码。

http://nuitka.net/

你没有解释为什么你觉得需要加密/解密。 答案可能会对提出的任何建议产生重大影响。

例如,假设您正在尝试保护知识产权,但就像在python中编码的便利性一样。 如果这是你的动力,请考虑cython – http://cython.org

但是,假设您更关注安全性(即:防止有人在未经用户许可的情况下更改代码)。 在这种情况下,你可以考虑某种嵌入式加载器,在调用嵌入式python解释器之前校验你的python源代码。

我确定你可能想要加密其他几十个原因。