Java SHA1 computeSHA1(byte[] ba)

Here you can find the source of computeSHA1(byte[] ba)

Description

computes the SHA1 hashcode for the passed byte array.

License

Open Source License

Parameter

Parameter Description
ba byte array.

Return

SHA1 string.

Declaration

public static String computeSHA1(byte[] ba) 

Method Source Code

//package com.java2s;
/*//ww w  .  java2  s  .  c o  m
 * FlexUtils.java
 *
 * Created on Mar 17, 2009 11:17:41 AM
 *
 * Copyright (C) 2009 Jayson Yu
 *
 * This program is free software; you can redistribute it and/or modify it under the terms of the
 * GNU General Public License as published by the Free Software Foundation; either version 2 of the
 * License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without
 * even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
 * General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License along with this program; if not,
 * write to the Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
 *
 */

import java.io.BufferedInputStream;

import java.io.ByteArrayInputStream;

import java.io.InputStream;

import java.security.DigestInputStream;
import java.security.MessageDigest;

import java.util.Formatter;

public class Main {
    /**
     * computes the SHA1 hashcode for the passed byte array.
     *
     * @param  ba byte array.
     * @return SHA1 string.
     */
    public static String computeSHA1(byte[] ba) {
        String hash = null;
        try {

            MessageDigest sha1 = MessageDigest.getInstance("SHA1");
            InputStream is = new ByteArrayInputStream(ba);
            BufferedInputStream bis = new BufferedInputStream(is);

            DigestInputStream dis = new DigestInputStream(bis, sha1);

            while (dis.read() != -1) {
            }
            ;

            byte[] h = sha1.digest();

            Formatter formatter = new Formatter();

            for (byte b : h) {
                formatter.format("%02x", b);
            }

            hash = formatter.toString();

        } catch (Exception e) {
            e.printStackTrace();
        }
        return hash;
    }
}

Related

  1. computeSha1(byte[] data)
  2. computeSHA1(ByteBuffer convertme, int offset, int len)
  3. computeSha1(ReadableByteChannel channel)
  4. computeSha1AsHexString(String strToHash)