'How to encrypt a code object in python for both windows and linux
How to Encrypt a code object to base64, bytes, sha256 etc any of them but that must support both of windows and Linux/Termux. I have tried marshal.dumps but it only work on that os where it was made. Like: I converted that code object to bytes with marshal.dumps on windows. But it only runs on windows, when I move that code to termux/linux, it shows Segmentation Fault. And if I convert to bytes with the same method on linux/termux, and then move that converted code to windows, it shows a dialog box and says python is not responding. The main code is on github. Here is a sample code:
my_code="print('This is encrypted code')"
enc_code=compile(my_code, 'string', 'exec')
# i want to encrypt this enc_code that supports both windows and linux
Edit:
There should be a decrypt method. I also want to decrypt that code object and execute that with exec function. Eg:
code=compile('print("Sometext")', 'nothing', 'exec')
code.encrypted_value='iurefbiuyrencuigfbc8yoiwusenowrov'
And decrypt that encrypted value then execute it:
exec('iurefbiuyrencuigfbc8yoiwusenowrov'.decrypted_code_object)
Solution 1:[1]
You can use cryptography library, havent checked it but I think it is compatible with both linux and windows.
from cryptography.fernet import Fernet
my_code="print('This is encrypted code')"
key=Fernet.generate_key()
print (key) #SAVE THIS KEY this key will be used to decrypt
## Encryption
f=Fernet(key)
encrypted_text=f.encrypt(my_code.encode()) #encrypting your code
print (encrypted_text)
### Decryption
f=Fernet(key) #passing the key you saved
decrypted_text=f.decrypt(encrypted_text) #decrypting the code
print(decrypted_text)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 |
