/**
* @author ahmed.ettoumi@gmail.com
* Calculate the hashcode or the checksum of the file on an HEX format
*
* @param file : the file that we want to calculate it's hashcode/checksum
* @param hashingAlogrithm : SHA-0, SHA-1, and SHA-2 OR SHA-224, SHA-256, SHA-384, and SHA-512
* @return HEX format of the checksum
* @throws NoSuchAlgorithmException
* @throws IOException
*/
public static String getChecksumFromFile(File file, String hashingAlogrithm)
throws NoSuchAlgorithmException, IOException {
MessageDigest md = MessageDigest.getInstance(hashingAlogrithm);
FileInputStream fis = null;
StringBuffer hexString = new StringBuffer();
String intToHex;
try {
fis = new FileInputStream(file);
byte[] dataBytes = new byte[1024];
int nread = 0;
while ((nread = fis.read(dataBytes)) != -1) {
md.update(dataBytes, 0, nread);
};
byte[] mdbytes = md.digest();
// convert the byte to hex format
for (int i = 0; i < mdbytes.length; i++) {
intToHex = Integer.toHexString(0xFF & mdbytes[i]);
if (intToHex.length() == 1) {
intToHex = "0".concat(intToHex);
}
hexString.append(intToHex);
}
LOGGER.debug("The Hash Code using {} algorithm is : {} ", hashingAlogrithm,
hexString.toString());
} finally {
if (fis != null) {
fis.close();
}
}
return hexString.toString();
}
Calulate Checksum (Hashcode) of File in Java
Inscription à :
Articles (Atom)
Aucun commentaire:
Enregistrer un commentaire