MCU 简单实现混淆存储
主要是防止明文存储密钥,直接被从编译后的二级制看到密钥。
过程比较简单,使用加法扰动,然后使用亦或进行混淆。里面只有加减运算和亦或,MCU 实现也比较容易。
# obfuscate_verify.py # Obfuscation key identical to the one used in C code OBF_KEY = bytes([0x5B, 0xC3, 0x1F, 0x8B, 0xB2, 0x4A, 0xE7, 0x92]) def obfuscate(data: bytes) -> bytes: """Python implementation matching the C logic: add index + XOR with key""" out = bytearray() for i, b in enumerate(data): temp = (b + i) & 0xFF # Additive perturbation (emulate uint8_t wrap-around) obf_byte = temp ^ OBF_KEY[i % len(OBF_KEY)] out.append(obf_byte) return bytes(out) def deobfuscate(obf_data: bytes) -> bytes: """Deobfuscation: first XOR, then subtract index""" out = bytearray() for i, b in enumerate(obf_data): temp = b ^ OBF_KEY[i % len(OBF_KEY)] orig_byte = (temp - i) & 0xFF # Subtraction must also respect uint8_t behavior (mod 256) out.append(orig_byte) return bytes(out) def bytes_to_hex(data: bytes) -> str: """Convert binary data to uppercase HEX string""" return data.hex().upper() def hex_to_bytes(hex_str: str) -> bytes: """Convert HEX string back to binary data""" return bytes.fromhex(hex_str) # ===== Main test routine ===== if __name__ == "__main__": original_str = '81023E039DD1A4ABF19D66E06C3033B0' original = hex_to_bytes(original_str) print(f"Original (HEX): {original_str}") # Obfuscate obf = obfuscate(original) obf_hex = bytes_to_hex(obf) print(f"Obfuscated (HEX): {obf_hex}") # Simulate reading from storage (HEX string → binary) restored_bin = hex_to_bytes(obf_hex) # Deobfuscate deobf = deobfuscate(restored_bin) deobf_str = bytes_to_hex(deobf) print(f"Deobfuscated (HEX): {deobf_str}") # Verify correctness assert original == deobf, "❌ Deobfuscation failed!" print("✅ Success: Original == Deobfuscated")
等效的 C 语言实现:
#include "Obfuscate.h" // contains extern declaration of ObKey[OB_KEY_LEN] /* Intentional wrap-around obfuscation; len must be <= 255 */ void Obfuscate(const uint8 *in, uint8 *out, uint8 len) { for (uint8 i = 0; i < len; i++) { uint8 temp = (uint8)(in[i] + i); /* Add index with uint8 wrap */ out[i] = temp ^ ObKey[i % OB_KEY_LEN]; } } /* Inverse of obfuscation; len must match original */ void Deobfuscate(const uint8 *in, uint8 *out, uint8 len) { for (uint8 i = 0; i < len; i++) { uint8 temp = in[i] ^ ObKey[i % OB_KEY_LEN]; out[i] = (uint8)(temp - i); /* Subtract index with uint8 wrap */ } }
可以使用上面的 python 脚本,生成混淆字段直接包含在代码中,使用时候调用 deobfuscate 恢复即可。
——————无论在哪里做什么,只要坚持服务、创新、创造价值,其他的东西自然都会来的。

浙公网安备 33010602011771号