I implemented this example of jar file which checks it's own checksum:
File currentJavaJarFile = new File(MainApp.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String jarFile = currentJavaJarFile.getAbsolutePath();// + "jarChecksumTest-1.0.jar";
byte[] data = Files.readAllBytes(Paths.get(jarFile));
MessageDigest complete = MessageDigest.getInstance(data);
MessageDigest md = MessageDigest.getInstance("SHA-256");
md.update(complete.toString().getBytes());
byte byteData[] = md.digest();
// convert the byte to hex format
StringBuilder sb = new StringBuilder();
for (int i = 0; i < byteData.length; i++)
{
sb.append(Integer.toString((byteData[i] & 0xff) + 0x100, 16).substring(1));
}
if ("L9ThxnotKPzthJ7hu3bnORuT6xI=".equals(sb.toString()))
{
System.out.println("Success!!!");
}
But then I run the file I get this message:
Caused by: java.security.NoSuchAlgorithmException: D:\.....\target\jarChecksumTest-1.0.jar MessageDigest not available
How I can solve this issue?
Try this code, it is running fine. You may choose any algorithm whether it is SHA/MD5
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
public class Checksum
{
public static void main(String ar[])
{
File currentJavaJarFile = new File(Checksum.class.getProtectionDomain().getCodeSource().getLocation().getPath());
String filepath = currentJavaJarFile.getAbsolutePath();
StringBuilder sb = new StringBuilder();
try
{
MessageDigest md = MessageDigest.getInstance("SHA-256");// MD5
FileInputStream fis = new FileInputStream(filepath);
byte[] dataBytes = new byte[1024];
int nread = 0;
while((nread = fis.read(dataBytes)) != -1)
md.update(dataBytes, 0, nread);
byte[] mdbytes = md.digest();
for(int i=0; i<mdbytes.length; i++)
sb.append(Integer.toString((mdbytes[i] & 0xff) + 0x100 , 16).substring(1));
}
catch(NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch(IOException e)
{
e.printStackTrace();
}
System.out.println("Checksum: "+sb);
}
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments