ExFAT boot checksum的python實現

前面的文章提到了ExFAT boot checksum出錯時的錯誤提醒,這裏如果需要確認boot checksum是否正確,需要將boot checusum的算法實現一遍.

這裏採用了python來實現.

boot checksum算法參考下面:

exFAT Boot Checksum

This sector contains a repeating 32-bit checksum of the previous 11 sectors. The checksum calculation excludes VolumeFlags and PercentInUse fields in Boot Sector (bytes 106, 107, 112). The checksum is repeated until the end of the sector. The number of repetitions depends on the size of the sector.

  UNIT32 BootChecksum(constunsignedchardata[], intbytes)
{
UINT32 checksum   =   0; 
for (inti = 0; i < bytes; i++)
{
if (i == 106 || i == 107 || i == 112)
continue;
checksum = (checksum<<31) | (checksum>> 1) + data[i];
}
returnchecksum;

 

這裏需要提取到ExFAT的boot sectors,可以採用WinHex來獲取,通過winHex來open對應的disk,copy前12個sector的數據到文本即可.

參考下面這個例子:

 

可以看到11 sector是前0~10 sectors 的checksum,它是一個DWORD型的整數,在這個sector中一直重複.

 

有了上門的算法和數據,我們就可以來實現並驗證算法,python code如下:

 

#!/usr/bin/python

#import os

if __name__ == '__main__':
    dir = 'C:\\Users\\admin\\Desktop\\python_script\\'
    file = 'ExFATCheckSum.TXT'
    fd = open(dir + file, 'r')
    checksum = 0
    ind = 0
    for (num,line) in enumerate(fd):
        if num > 10:
            break
        for start in range(0,len(line),2):
            if 106==ind or 107==ind or 112==ind:
                ind += 1
                continue
            if start >= len(line)-2:
                break
            #print '%s:%d' %(line[start:start+2], int(line[start:start+2], 16))
            checksum = long(((checksum<<31)&0xFFFFFFFF) | ((checksum>>1) & 0xFFFFFFFF) + long(line[start:start+2], 16))
            print 'sector:%d, byte:%d, checksum:%08x' %(num, ind, checksum)
            ind += 1
    print '%08x' %checksum

 

實驗結果參考:

checksum爲0xD9DE1E08,與上面的數據中的11 sector是一致的。

算法驗證OK。


 

發佈了67 篇原創文章 · 獲贊 12 · 訪問量 57萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章