Skip to content

Instantly share code, notes, and snippets.

@mutterer
Created February 2, 2021 16:07
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mutterer/378d0f302aedb8e86b3511f113f2a321 to your computer and use it in GitHub Desktop.
Save mutterer/378d0f302aedb8e86b3511f113f2a321 to your computer and use it in GitHub Desktop.
This plugin can be used to "seal" your *.ijm files
import java.io.File;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.security.MessageDigest;
import ij.IJ;
import ij.gui.GenericDialog;
import ij.plugin.PlugIn;
/**
* This plugin can be used to "seal" your *.ijm files by adding a hash of the file content to the filename.
* Then you can use the same plugin to run these files, and the hash will be checked against the current file content,
* and the macro is run if the content didn't change, or it will fail with a message that the macro was changed.
*
* @author jmutterer
*/
public class Safe_Macro implements PlugIn {
public void run(String arg) {
GenericDialog gd = new GenericDialog("Select Macro File to Seal");
gd.addChoice("Action", new String[] { "Seal", "Run" }, "Seal");
gd.addChoice("Hash method", new String[] { "MD5", "SHA-256" }, "MD5");
gd.addFileField("Macro file", IJ.getDirectory("imagej"));
gd.showDialog();
if (gd.wasCanceled())
return;
String action = gd.getNextChoice();
String method = gd.getNextChoice();
String macro = gd.getNextString();
if (!macro.toLowerCase().endsWith(".ijm")) {
IJ.error("Only works with *.ijm macros");
return;
}
if (action == "Seal") {
File f1 = new File(macro);
File f2 = new File(macro.substring(0, macro.lastIndexOf(".")) + "_" + getHash(macro, method) + ".ijm");
boolean success = f1.renameTo(f2);
if (!success)
IJ.error("Couldn't rename macro.");
} else {
String fileHash = getHash(macro, method);
String filenameHash = macro.substring(macro.lastIndexOf("_") + 1, macro.lastIndexOf("."));
if (fileHash.equals(filenameHash)) {
IJ.runMacroFile(macro);
} else {
IJ.error("Couldn't run macro. Hash do not match.");
}
}
}
private String getHash(String s, String m) {
try {
MessageDigest digest = MessageDigest.getInstance(m);
Path path = Paths.get(s);
byte[] encodedhash = digest.digest(Files.readAllBytes(path));
return bytesToHex(encodedhash);
} catch (Exception e) {
}
return "0";
}
private static String bytesToHex(byte[] hash) {
StringBuilder hexString = new StringBuilder(2 * hash.length);
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment