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

后端 未结 3 810
遇见更好的自我
遇见更好的自我 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:32

    public static String computeFileSHA1( File file ) throws IOException
    {
        String sha1 = null;
        MessageDigest digest;
        try
        {
            digest = MessageDigest.getInstance( "SHA-1" );
        }
        catch ( NoSuchAlgorithmException e1 )
        {
            throw new IOException( "Impossible to get SHA-1 digester", e1 );
        }
        try (InputStream input = new FileInputStream( file );
             DigestInputStream digestStream = new DigestInputStream( input, digest ) )
        {
            while(digestStream.read() != -1){
                // read file stream without buffer
            }
            MessageDigest msgDigest = digestStream.getMessageDigest();
            sha1 = new HexBinaryAdapter().marshal( msgDigest.digest() );
        }
        return sha1;
    }
    

提交回复
热议问题