Java SHA1 computeSha1(ReadableByteChannel channel)

Here you can find the source of computeSha1(ReadableByteChannel channel)

Description

compute Sha

License

Open Source License

Declaration

public static String computeSha1(ReadableByteChannel channel)
            throws IOException 

Method Source Code

//package com.java2s;
import java.io.IOException;

import java.nio.ByteBuffer;
import java.nio.channels.ReadableByteChannel;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class Main {
    private static final char[] HEX_CODE = "0123456789abcdef".toCharArray();

    public static String computeSha1(ReadableByteChannel channel)
            throws IOException {
        final MessageDigest sha1 = newSHA1();
        final ByteBuffer buf = ByteBuffer.allocate(8192);
        while (channel.read(buf) != -1) {
            buf.flip();//w ww.jav  a2s.  c  om
            sha1.update(buf);
            buf.clear();
        }
        return toHexString(ByteBuffer.wrap(sha1.digest()));
    }

    public static MessageDigest newSHA1() {
        try {
            return MessageDigest.getInstance("SHA-1");
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("SHA-1");
        }
    }

    public static String toHexString(ByteBuffer buffer) {
        final StringBuilder r = new StringBuilder(buffer.remaining() * 2);
        while (buffer.hasRemaining()) {
            final byte b = buffer.get();
            r.append(HEX_CODE[(b >> 4) & 0xF]);
            r.append(HEX_CODE[(b & 0xF)]);
        }
        return r.toString();
    }
}

Related

  1. computeSHA1(byte[] ba)
  2. computeSha1(byte[] data)
  3. computeSHA1(ByteBuffer convertme, int offset, int len)
  4. computeSha1AsHexString(String strToHash)
  5. computeSHA1Hash(byte[] data)
  6. digestSHA1(byte[] data)
  7. digestSHA1(String data)