MicroPython⼊坑记(四)关于MicroPython的代码保护
脚本开发东西,可能⾯临的第⼀个问题就是:拷给别⼈,代码怎么写的他不就都知道了?不⾏,我要保住我的⼩秘密!
先说下结果:没有攻不破的堡垒,即使你写成C语⾔,只要能拿到⼆进制结果,都可以反汇编逆向出你是怎么实现的,关键是值不值得
python转java代码另外,这跟逆向者对系统的了解程度有关,⽐如对⽅连代码都不会上传,那你即使把源⽂件放进去也他也⽆可奈何。
好了,⾔归正传,我们知道普通python有个编译成字节码的功能,也就是源代码会在解释时先编译成⼀个类似java中间代码的结果,这是不可读的(但是这也不排除反编译的可能,毕竟JAVA的class⽂件是有反编译软件的)。
micropython也有这个功能,不过这个⽂件的扩展名是mpy,也不能在运⾏时⾃动⽣成,需要⼀款软件:,这是micropython官⽅提供的,可以⽤python pip直接安装,安装完成后,可以运⾏ pythonfile,py,就可以⽣成⼀个pythonfile.mpy的字节码⽂件,这⽂件使⽤跟py⽂件是等效的。把所有⽂件⽣成mpy,可以在⼀定程度上保护你的代码。
更进⼀步的⽅式:把mpy⽂件藏到固件中去,这不光能保护代码,还能降低程序的内存占⽤,官⽅的描述如下:
Cross-installing packages with freezing
For the low-memory , the process described in the previous section does not provide the most efficient resource usage,because the packages are installed in the source form, so need to be compiled to the bytecome on each import. This compilation requires RAM, and the resulting bytecode is also stored in RAM, reducing its amount available for storing application data. Moreover, the process above requires presence of the filesystem on a device, and the most resource-constrained devices may not even have it.
The bytecode freezing is a process which resolves all the issues mentioned above:
The source code is pre-compiled into bytecode and store as such.
The bytecode is stored in ROM, not RAM.
Filesystem is not required for frozen packages.
Using frozen bytecode requires building the executable (firmware) for a given  from the C source code. Consequently, the process is:
1. Follow the instructions for a particular port on setting up a toolchain and building the port. For example, for ESP8266 port, study
instructions in ports/esp8266/README.md and follow them. Make sure you can build the port and deploy the resulting
executable/firmware successfully before proceeding to the next steps.
2. Build  and make sure it is in your PATH and you can execute micropython.
3. Change to port’s directory (e.g. ports/esp8266/ for ESP8266).
4. Run make clean-frozen. This step cleans up any previous modules which were installed for freezing (consequently, you need to skip this
step to add additional modules, instead of starting from scratch).
5. Run micropython -m upip install -p modules <packages>... to install packages you want to freeze.
6. Run make clean.
7. Run make.
After this, you should have the executable/firmware with modules as the bytecode inside, which you can deploy the usual way.
⼤体的意思是这样的:运⾏py⽂件不能有效的使⽤内存资源,因为代码执⾏时需要被编译成bytecode代码,该编译需要RAM,⽣成的字节码也存在RAM中,这就降低了可⽤内存。并且存储py⽂件需要⽂件系统,⽽⼀些嵌⼊设备本⾝不存在⽂件系统。
嗯,神⼀样的保护功能,不但降低了内存占⽤,还把字节码藏到了固件中,代价就是需要⾃⼰编译micropython固件。

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。