Java examples for Security:SHA
Retrieves the SHA-1 sum of a file.
import java.io.BufferedInputStream; import java.io.File; import java.io.FileInputStream; import java.io.IOException; import java.math.BigInteger; import java.security.MessageDigest; import java.security.NoSuchAlgorithmException; import java.util.Locale; public class Main{ public static void main(String[] argv) throws Exception{ File file = new File("Main.java"); System.out.println(sha1sum(file)); }//from w w w . jav a2 s . co m private static final int BUFFER = 8192; private static final String SHA1 = "SHA"; /** * Retrieves the SHA-1 sum of a file. * * @param file - The file to check. * @return The SHA1 sum. * @throws IllegalArgumentException If the file is <code>null</code> or is * not a file. * @throws IOException If an error occurs while reading the file. * @throws NoSuchAlgorithmException If it is impossible to produce a * checksum by using the specified method/algorithm. */ public static String sha1sum(final File file) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { return computeCheckSum(file, SHA1); } /** * @param file * @param algorithm * @return * @throws IllegalArgumentException If the file is <code>null</code> or is * not a file. * @throws IOException If an error occurs while reading the file. * @throws NoSuchAlgorithmException If it is impossible to produce a * checksum by using the specified method/algorithm. */ private static String computeCheckSum(final File file, final String algorithm) throws IllegalArgumentException, IOException, NoSuchAlgorithmException { if (file == null) throw new IllegalArgumentException( "The file for which to check the sum cannot be null."); if (!file.isFile()) throw new IllegalArgumentException("Must be a file."); BufferedInputStream bis = null; try { final MessageDigest checksum = MessageDigest .getInstance(algorithm); bis = new BufferedInputStream(new FileInputStream(file)); int length; final byte[] data = new byte[BUFFER]; while ((length = bis.read(data, 0, BUFFER)) != -1) { checksum.update(data, 0, length); } bis.close(); final byte[] bytes = checksum.digest(); return toHex(bytes).toUpperCase(Locale.ENGLISH); } finally { CommonUtils.closeStreamQuietly(bis); } } /** * Converts an array of byte into an hexadecimal string format. * * @param bytes - The byte array to convert * @return The string in hexadecimal format */ private static String toHex(final byte[] bytes) { final BigInteger bigInt = new BigInteger(1, bytes); return bigInt.toString(16); } }