Java SHA1 sha1sum(File file)

Here you can find the source of sha1sum(File file)

Description

shasum

License

Apache License

Declaration

public static String sha1sum(File file) throws IOException 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;

import java.io.RandomAccessFile;

import java.math.BigInteger;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    public static String sha1sum(File file) throws IOException {
        InputStream in = new FileInputStream(file);
        String cs = checksum("SHA-1", in);
        in.close();/* ww  w . j av a2 s.  c o m*/
        return cs;
    }

    public static String checksum(String algorithm, InputStream in) throws IOException {
        MessageDigest md;

        try {
            md = MessageDigest.getInstance(algorithm);
        } catch (NoSuchAlgorithmException e) {
            throw new IOException(e);
        }

        return checksum(md, in);
    }

    public static String checksum(MessageDigest md, InputStream in) throws IOException {
        byte[] buf = new byte[8 * 1024];

        while (true) {
            int read = in.read(buf);

            if (read == -1) {
                break;
            }

            md.update(buf, 0, read);
        }

        String result = new BigInteger(1, md.digest()).toString(16);

        return result;
    }

    public static ByteBuffer read(File file, long offset, int length) throws IOException {
        FileChannel chan = channel(file, false);

        ByteBuffer buf = ByteBuffer.allocate(length);
        chan.position(offset);

        while (buf.remaining() > 0) {
            if (chan.read(buf) <= 0) {
                throw new IOException("Failed to read from channel.");
            }
        }

        buf.rewind();
        chan.close();

        return buf;
    }

    public static String toString(File file, String charset) throws IOException {
        ByteBuffer buf = read(file, 0, (int) file.length());
        return new String(buf.array(), buf.arrayOffset(), buf.remaining(), charset);
    }

    public static FileChannel channel(File file, boolean writeable) throws IOException {
        String opts = writeable ? "rw" : "r";
        RandomAccessFile fd = new RandomAccessFile(file, opts);
        FileChannel chan = fd.getChannel();

        return chan;
    }
}

Related

  1. sha1Java(String password)
  2. sha1Sum(byte[] ba)
  3. sha1sum(byte[] data, Integer startIdxInc, Integer stopIdxExc)
  4. sha1sum(byte[] input, int length)
  5. sha1sum(File file)
  6. SHA1Sum(final @Nonnull byte[] bytes)
  7. sha1sum(final String data)
  8. sha1sum(InputStream file)
  9. sha1ToHex(String input, String encoding)