/** * Get the md5 value of the filepath specified file * @param filePath The filepath of the file * @return The md5 value */ public String fileToMD5(String filePath) { InputStreaminputStream=null; try { inputStream = newFileInputStream(filePath); // Create an FileInputStream instance according to the filepath byte[] buffer = newbyte[1024]; // The buffer to read the file MessageDigestdigest= MessageDigest.getInstance("MD5"); // Get a MD5 instance intnumRead=0; // Record how many bytes have been read while (numRead != -1) { numRead = inputStream.read(buffer); if (numRead > 0) digest.update(buffer, 0, numRead); // Update the digest } byte [] md5Bytes = digest.digest(); // Complete the hash computing return convertHashToString(md5Bytes); // Call the function to convert to hex digits } catch (Exception e) { returnnull; } finally { if (inputStream != null) { try { inputStream.close(); // Close the InputStream } catch (Exception e) { } } } } /** * Get the sha1 value of the filepath specified file * @param filePath The filepath of the file * @return The sha1 value */ public String fileToSHA1(String filePath) { InputStreaminputStream=null; try { inputStream = newFileInputStream(filePath); // Create an FileInputStream instance according to the filepath byte[] buffer = newbyte[1024]; // The buffer to read the file MessageDigestdigest= MessageDigest.getInstance("SHA-1"); // Get a SHA-1 instance intnumRead=0; // Record how many bytes have been read while (numRead != -1) { numRead = inputStream.read(buffer); if (numRead > 0) digest.update(buffer, 0, numRead); // Update the digest } byte [] sha1Bytes = digest.digest(); // Complete the hash computing return convertHashToString(sha1Bytes); // Call the function to convert to hex digits } catch (Exception e) { returnnull; } finally { if (inputStream != null) { try { inputStream.close(); // Close the InputStream } catch (Exception e) { } } } }
/** * Convert the hash bytes to hex digits string * @param hashBytes * @return The converted hex digits string */ privatestatic String convertHashToString(byte[] hashBytes) { StringreturnVal=""; for (inti=0; i < hashBytes.length; i++) { returnVal += Integer.toString(( hashBytes[i] & 0xff) + 0x100, 16).substring(1); } return returnVal.toLowerCase(); }