Skip to content

Instantly share code, notes, and snippets.

@lamergameryt
Created June 17, 2021 04:30
Show Gist options
  • Save lamergameryt/cc34fade1751426e164c3532f7c421cc to your computer and use it in GitHub Desktop.
Save lamergameryt/cc34fade1751426e164c3532f7c421cc to your computer and use it in GitHub Desktop.
Simple MD5 Hash Changer made in Java
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;
import java.security.MessageDigest;
import java.security.SecureRandom;
public class HashChanger {
private static final SecureRandom random = new SecureRandom();
private static int filesProcessed;
public static void main(String[] args) {
if (args.length == 0) {
System.out.println("No files were passed, cancelling operation.");
return;
}
for (String file : args) {
Path p = Paths.get(file);
String lastHash = fileToMD5(p.toString());
boolean success = changeMD5(p);
if (success) {
String newHash = fileToMD5(p.toString());
System.out.println(p.getFileName() + " : " + lastHash + " -> " + newHash);
filesProcessed++;
}
}
if (filesProcessed == 0) {
System.out.println("No files were hashed.");
} else {
System.out.println();
System.out.println("The hash of " + filesProcessed + " files were changed.");
}
}
private static boolean changeMD5(Path path) {
try {
int nullBytes = random.nextInt(5) + 2;
byte[] bytes = new byte[nullBytes];
for (int i = 0; i < nullBytes; i++) {
bytes[i] = (byte) 0;
}
Files.write(path, bytes, StandardOpenOption.APPEND);
return true;
} catch (IOException e) {
System.out.println("The file " + path.getFileName().toString() + " failed to undergo MD5 Hash Change.");
return false;
}
}
public static String fileToMD5(String filePath) {
try (InputStream inputStream = new FileInputStream(filePath)) {
byte[] buffer = new byte[1024];
MessageDigest digest = MessageDigest.getInstance("MD5");
int numRead = 0;
while (numRead != -1) {
numRead = inputStream.read(buffer);
if (numRead > 0)
digest.update(buffer, 0, numRead);
}
byte[] md5Bytes = digest.digest();
return convertHashToString(md5Bytes);
} catch (Exception e) {
return null;
}
}
private static String convertHashToString(byte[] md5Bytes) {
StringBuilder returnVal = new StringBuilder();
for (byte md5Byte : md5Bytes) {
returnVal.append(Integer.toString((md5Byte & 0xff) + 0x100, 16).substring(1));
}
return returnVal.toString().toUpperCase();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment