웹 개발

java로 exe 파일 읽어서 특정 문자열을 바꾸어 저장하기

노루아부지 2019. 8. 23. 22:22

1. String 이용

public static void main(String[] args) throws Exception
{
	Path newP = Paths.get("d:/result.exe");
	String content = binaryFileToHexString("d:/attach.exe");

	System.out.println(content.indexOf("{exec}"));

	String result = content.substring(0, content.indexOf("7B657865637D")) + "7777772E6E617665722E636F6D" + content.substring(content.indexOf("7B657865637D") + "7777772E6E617665722E636F6D".length());
	Files.write(newP, hexStringToByteArray(result));
}

public static String binaryFileToHexString(final String path)
		throws FileNotFoundException, IOException
{
	final int bufferSize = 512;
	final byte[] buffer = new byte[bufferSize];
	final StringBuilder sb = new StringBuilder();

	// open the file
	FileInputStream stream = new FileInputStream(path);
	int bytesRead;

	// read a block
	while ((bytesRead = stream.read(buffer)) > 0)
	{
		// append the block as hex
		for (int i = 0; i < bytesRead; i++)
		{
			sb.append(String.format("%02X", buffer[i]));
		}
	}

	stream.close();
	return sb.toString();
}

public static byte[] hexStringToByteArray(String s) {
	int len = s.length();
	byte[] data = new byte[len / 2];

	for (int i = 0; i < len; i += 2) {
		data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4)
                            + Character.digit(s.charAt(i+1), 16));

	}
	return data;
}

// * 7B657865637D는 {exec}를 의미
// * 7777772E6E617665722E636F6D는 www.naver.com을 의미
// * 파일을 binary로 읽어서 hex값 형태의 String으로 저장한 후에 substring하여 다시 binary로 변환하여 저장
// * 만약 단순 substring을 사용하게 되면 에러 발생.

 

2. byte 이용

public static void main(String[] args) {
	FileInputStream fis = null;
	FileOutputStream fos = null;

	try{
		File f = new File("d:/attach.exe");
		int pos = 5656;  // 치환 문자열의 시작 위치
		int size = (int)f.length();
		fis = new FileInputStream("d:/attach.exe");
		fos = new FileOutputStream("d:/result.exe");
		byte[] buffer = new byte[size];
		int readcount = 0;

		while((readcount = fis.read(buffer)) != -1){
        	// 변환하고자 하는 문자열
			String s = "www.naver.com";
			for(int i=0; i<s.length(); i++) {
				buffer[pos + i] = (byte)s.charAt(i);
			}

			fos.write(buffer,0,readcount);
		}

		System.out.println("파일복사가 완료되었습니다.");
	}
    catch(Exception ex) {
		System.out.println(ex);
	}
    finally {
		try {
			fis.close();
		} catch (IOException ex) {}
		
        try {
			fos.close();
		} catch (IOException ex) {}
	}
}

 

3. byte 이용 다른 방법

 

try{
	int pos = 5656;
	byte[] buffer = Files.readAllBytes(Paths.get("d:/attach.exe"));

	String s = "www.tistory.com";
 
	for(int i=0; i<s.length(); i++) {
		buffer[pos + i] = (byte)s.charAt(i);
	}

	Files.write(Paths.get("d:/44444.exe"), buffer);
	System.out.println("파일복사가 완료되었습니다.");
}
catch(Exception ex) {
	System.out.println(ex);
}
finally{}
728x90
loading