john pfeiffer
  • Home
  • Categories
  • Tags
  • Archives

CalculateSha1

//2012-12-27 johnpfeiffer
//TODO: make static
package net.kittyandbear;

import java.io.BufferedInputStream;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.security.DigestInputStream;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Formatter;

public class CalculateSha1 {

    private MessageDigest algorithm = null;
    private String sha1 = "";

    CalculateSha1( String filename ) throws IOException {
        if( filename == null || filename.isEmpty() ) {
            throw new IllegalArgumentException( "ERROR: filename cannot be null or empty" );
        }

        try {
            algorithm = MessageDigest.getInstance( "SHA-1" );
        } catch( NoSuchAlgorithmException e ) {
            e.printStackTrace();
        }

        FileInputStream filestream = new FileInputStream( filename );
        sha1 = calculateHashFromInputStream( filestream, algorithm );
    }

    CalculateSha1( InputStream data ) throws IOException {
        if( data == null ) {
            throw new IllegalArgumentException( "ERROR: inputStream cannot be null" );
        }

        try {
            algorithm = MessageDigest.getInstance( "SHA-1" );
        } catch( NoSuchAlgorithmException e ) {
            e.printStackTrace();
        }

        sha1 = calculateHashFromInputStream( data, algorithm );
    }

    public static String computeSHA1Hash( byte[] rawData ) throws Exception {
        StringBuilder sb = new StringBuilder();
        MessageDigest md = MessageDigest.getInstance( "SHA" );
        md.update( rawData );
        byte[] digest = md.digest();
        for( byte b : digest ) {
            sb.append( String.format( "%02x", b & 0xff ) );
        }
        return sb.toString();
    }


    public String getSha1() {
        return sha1;
    }



    private static String calculateHashFromInputStream( InputStream inputStream, MessageDigest algorithm ) throws IOException {
        byte[] hash = null;
        BufferedInputStream bufferedstream = new BufferedInputStream( inputStream );
        DigestInputStream digeststream = new DigestInputStream( bufferedstream, algorithm );

        while( digeststream.read() != -1 ) {}
        hash = algorithm.digest();
        digeststream.close();

        return byteArrayToHex( hash );
    }

    private static String byteArrayToHex( byte[] array ) {
        Formatter formatter = new Formatter();
        for( byte b : array ) {
            formatter.format( "%02x", b );
        }
        return formatter.toString();
    }

} // end class

  • « CalculateSha1Test Parameterized Stream From String
  • file write inputstream to outputstream »

Published

Dec 27, 2012

Category

java-classes

~187 words

Tags

  • calculatesha1 1
  • classes 92
  • java 252
  • sha1 6