MicroPython入坑記(四)關於MicroPython的代碼保護


腳本開發東西,可能面臨的第一個問題就是:拷給別人,代碼怎么寫的他不就都知道了?不行,我要保住我的小秘密!

先說下結果:沒有攻不破的堡壘,即使你寫成C語言,只要能拿到二進制結果,都可以反匯編逆向出你是怎么實現的,關鍵是值不值得

另外,這跟逆向者對系統的了解程度有關,比如對方連代碼都不會上傳,那你即使把源文件放進去也他也無可奈何。

好了,言歸正傳,我們知道普通python有個編譯成字節碼的功能,也就是源代碼會在解釋時先編譯成一個類似java中間代碼的結果,這是不可讀的(但是這也不排除反編譯的可能,畢竟JAVA的class文件是有反編譯軟件的)。

micropython也有這個功能,不過這個文件的擴展名是mpy,也不能在運行時自動生成,需要一款軟件:mpy-cross.exe,這是micropython官方提供的,可以用python pip直接安裝,安裝完成后,可以運行mpy-cross.exe pythonfile,py,就可以生成一個pythonfile.mpy的字節碼文件,這文件使用跟py文件是等效的。把所有文件生成mpy,可以在一定程度上保護你的代碼。

更進一步的方式:把mpy文件藏到固件中去,這不光能保護代碼,還能降低程序的內存占用,官方的描述如下:

Cross-installing packages with freezing

For the low-memory MicroPython ports, 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 MicroPython port 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 MicroPython Unix port 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固件。


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM