Java: How to create SHA-1 for a file?

后端 未结 3 809
遇见更好的自我
遇见更好的自我 2020-12-05 06:50

What is the best way to create a SHA-1 for a very large file in pure Java6? How to implement this method:

public abstract String createSha1(java.io.File file         


        
3条回答
  •  生来不讨喜
    2020-12-05 07:47

    Op requested the function to return a String of the SHA1, so I took @jeffs answer and added the missing conversion to String:

    /**
     * Read the file and calculate the SHA-1 checksum
     * 
     * @param file
     *            the file to read
     * @return the hex representation of the SHA-1 using uppercase chars
     * @throws FileNotFoundException
     *             if the file does not exist, is a directory rather than a
     *             regular file, or for some other reason cannot be opened for
     *             reading
     * @throws IOException
     *             if an I/O error occurs
     * @throws NoSuchAlgorithmException
     *             should never happen
     */
    private static String calcSHA1(File file) throws FileNotFoundException,
            IOException, NoSuchAlgorithmException {
    
        MessageDigest sha1 = MessageDigest.getInstance("SHA-1");
        try (InputStream input = new FileInputStream(file)) {
    
            byte[] buffer = new byte[8192];
            int len = input.read(buffer);
    
            while (len != -1) {
                sha1.update(buffer, 0, len);
                len = input.read(buffer);
            }
    
            return new HexBinaryAdapter().marshal(sha1.digest());
        }
    }
    

提交回复
热议问题