Skip to content

Instantly share code, notes, and snippets.

@Forgo7ten
Created November 8, 2021 14:14
Show Gist options
  • Save Forgo7ten/d8a453a721782ffbbc1c53a04060c924 to your computer and use it in GitHub Desktop.
Save Forgo7ten/d8a453a721782ffbbc1c53a04060c924 to your computer and use it in GitHub Desktop.
dex文件计算校验和
# coding=utf-8
# @File : dex_checksum.py
# @Desc : 计算dex的checksum
# @Author : https://www.52pojie.cn/thread-1070218-1-1.html
# @Time : 2021/11/8
# Adler-32算法如下步骤实现:
# 1. 定义两个变量varA、varB,其中varA初始化为1,varB初始化为0。
# 2. 读取字节数组的一个字节(假设该字节变量名为byte),计算varA = (varA + byte) mod 65521,然后可以计算出varB = (varA + varB) mod 65521。
# 3. 重复步骤2,直到字节数组全部读取完毕,得到最终varA、varB两个变量的结果。
# 4. 根据第三步得到的varA、varB两个变量,可得到最终校验和checksum = (varB << 16)+ varA。
import binascii
# 在这里填入dex的文件路径
dex_file_path = "C:/Users/Palmer/Desktop/classes.dex"
# 计算varA,varB
def CalculationVar(srcByte, vara, varb):
varA = vara
varB = varb
icount = 0
listAB = []
while icount < len(srcByte):
varA = (varA + srcByte[icount]) % 65521
varB = (varB + varA) % 65521
icount += 1
listAB.append(varA)
listAB.append(varB)
return listAB
# 根据varA,varB得到最终的校验和
def getCheckSum(varA, varB):
Output = (varB << 16) + varA
return Output
def main():
filename = dex_file_path
f = open(filename, 'rb') # f = open(filename, 'rb', True)
f.seek(0x0c)
VarA = 1
VarB = 0
flag = 0
CheckSum = 0
while True:
srcBytes = []
for i in range(1024): # 一次只读1024个字节,防止内存占用过大
ch = f.read(1)
if not ch: # 如果读取到末尾,设置标识符,然后退出读取循环
flag = 1
break
else:
ch = binascii.b2a_hex(ch) # 将字节转为int类型,然后添加到数组中
ch = str(ch, encoding='utf-8')
ch = int(ch, 16)
srcBytes.append(ch)
varList = CalculationVar(srcBytes, VarA, VarB)
VarA = varList[0]
VarB = varList[1]
if flag == 1:
CheckSum = getCheckSum(VarA, VarB)
break
print(f'[*] DEX FILENAME: {filename}')
print(f'[+] CheckSum = {hex(CheckSum)}')
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment