Linux教程網
Linux教程網
Linux教程網
您现在的位置: Linux教程網 >> UnixLinux >  >> Linux 程式設計 >> Linux 程式設計

CRC32 逆向演算法:用四個位元組改寫校驗值

CRC32 校驗應用很廣泛。本文提供一種演算法,透過添加 4 個位元組,實現任意 CRC32 校驗值之間的轉換——也就是逆向計算,讓你可以隨意修改檔案任意 4 個位元組,把 CRC32 改成想要的目標值。

原理

下面是一組 CRC32 計算過程。添加了四個位元組 00 ba ff 30 之後,原 CRC32 值 2be0dd1d 變成 eee8a9a6:

src32val:2be0dd1d ^ 00 -->x=1d
src32val:002be0dd ^
T(x) : 63066cd9
src32val:632d8c04 (現在計算的 CRC 值)

src32val:632d8c04 ^ 00-->x=04 x[4]
src32val:00632d8c ^
T(x) : 076dc419
src32val:070ee995

src32val:070ee995 ^ ba-->x=2f x[3]
src32val:00070ee9 ^
T(x) : abd13d59
src32val:abd633b0

src32val:abd633b0 ^ ff-->x=4f x[1]
src32val:00abd633 ^
T(x) : e6635c01
src32val:e6c88a32

src32val:e6c88a32 ^ 30-->x=02 x[0]
src32val:00e6c88a ^
T(x) : ee0e612c  tx
src32val:eee8a9a6 (添加 4 個字節後的目標 CRC 值)

關鍵事實是:CRC32 的 table 裡 256 個元素的最高位元是唯一不重複的。因此可以從 CRC 值倒推前四個 T(x) 值:

  1. 由最終的 CRC 值推導出前 4 個 T(x) 值,此時 T(x) 與 x 已知。
  2. 由原 CRC32 值結合 x 值,推導出 4 個要添加的未知位元組。

程式輸出

www.linuxidc.com @ www.linuxidc.com :~/sniffer/fw_tool$ ./a.out
crc32: reverse 4 bytes
crc32: enter 2 CRC value: src dst
632d8c04 eee8a9a6
Add those 4 bytes: ( 00 ba ff 30 ) to change CRC 632d8c04 to eee8a9a6
change  crc: 632d8c04 ==> eee8a9a6
reserve crc: eee8a9a6 ==> 632d8c04

頭文件 crc.h

//==========================================================================
//
//      crc.h
//
//      Interface for the CRC algorithms.
//==========================================================================

#ifndef __CRC32_H__
#define __CRC32_H__

// Gary S. Brown's 32 bit CRC
unsigned int cyg_crc32(unsigned char *s, int len);

// Gary S. Brown's 32 bit CRC, but accumulate the result from a
// previous CRC calculation
unsigned int cyg_crc32_accumulate(unsigned int crc, unsigned char *s, int len);

// Ethernet FCS Algorithm
unsigned int cyg_ether_crc32(unsigned char *s, int len);

// Ethernet FCS algorithm, but accumulate the result from a previous
// CRC calculation.
unsigned int cyg_ether_crc32_accumulate(unsigned int crc, unsigned char *s,
  int len);

/**
* add 4 bytes num[4] to change crc32 value from crc_src to crc_dst
* @return: 0 on success, -1 on error.
*/
int cyg_crc32_change(unsigned int crc_dst, unsigned int crc_src, uint8_t num[4]);

/**
* cyg_crc32_reserve - reserve CRC32 value by dropping data[len]
* @return: return the CRC value before data[len]
*/
unsigned int cyg_crc32_reserve(unsigned int crc, void *data, int len);

#endif // __CRC32_H__

這個技巧在韌體與映像檔處理上很實用:當映像檔帶有 CRC 校驗,而你只需要修改其中一小段資料(例如版本號、MAC 位址),就能反推出 4 個「補丁位元組」,讓修改後的檔案仍然通過原本硬體或 bootloader 的 CRC 檢查,不必重新計算並寫入新的校驗欄位。實作上最簡單的方式是先把 CRC32 的查表法表 T[256] 建出來,再依上述兩步驟做查表與反查即可。

Copyright © Linux教程網 All Rights Reserved