修复Dex文件头--Java源代码

本文介绍如何修复Android项目的Dex文件头,提供了一段Java源代码供直接使用,适用于需要修改dex文件的场景。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

由于需要在android项目中修改dex文件,所以自己实现了一个dex文件头修复。代码如下,可以直接拿来用。比较简单所以就不注释了。


public class FixDexHeaderUtil {

	public static void fix(String file) {
		byte[] fBytes = readFile(file);
		fix(fBytes);
		saveFile(fBytes, file);
	}

	private static byte[] readFile(String file) {
		FileInputStream fis = null;
		ByteArrayOutputStream bos = new ByteArrayOutputStream();
		try {
			fis = new FileInputStream(file);
			if (fis != null && bos != null) {
				int len = -1;
				byte[] buf = new byte[512];
				while ((len = fis.read(buf)) != -1) {
					bos.write(buf, 0, len);
					bos.flush();
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fis != null) {
				try {
					fis.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		byte[] fBytes = bos.toByteArray();
		if (bos != null) {
			try {
				bos.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		return fBytes;
	}

	private static void saveFile(byte[] fBytes, String file) {
		FileOutputStream fos = null;
		try {
			fos = new FileOutputStream(file);
			fos.write(fBytes);
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (fos != null) {
				try {
					fos.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
	}

	private static void fix(byte[] fBytes) {
		fixSha1Signature(fBytes);
		fixChecksum(fBytes);
	}

	private static void fixSha1Signature(byte[] fBytes) {
		MessageDigest sha1 = null;
		try {
			sha1 = MessageDigest.getInstance("SHA1");
			sha1.update(fBytes, 32, fBytes.length - 32);
			byte[] hashBytes = sha1.digest();
			for (int i = 0; i < hashBytes.length; i++) {
				fBytes[12 + i] = hashBytes[i];
			}
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
	}

	private static void fixChecksum(byte[] fBytes) {
		Adler32 al = new Adler32();
		al.update(fBytes, 12, fBytes.length - 12);
		int sum = (int) al.getValue();
		byte[] result = new byte[4];
		result[0] = (byte) sum;
		result[1] = (byte) (sum >> 8);
		result[2] = (byte) (sum >> 16);
		result[3] = (byte) (sum >> 24);
		for (int i = 0; i < result.length; i++) {
			fBytes[8 + i] = result[i];
		}
	}
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

番茄大圣

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值