Free, tested & ready to use examples : Java cryptography SHA1 SHA SHA-1 hash MD5
AnyExample.com
 
Web anyexample.com
 

Java simple class to compute SHA-1 hash

abstract 
SHA is a cryptographic message digest algorithm similar to MD5. SHA-1 hash considered to be one of the most secure hashing functions, producing a 160-bit digest (40 hex numbers) from any data with a maximum size of 264 bits. While Java has built in classes to compute SHA 1 hash, it's quite uneasy to use them for a simple task -- calculate SHA-1 hash and return 40 byte hexadecimal string.
compatible 
  • Sun Java 1.4 or higher

We use MessageDigest class, first setting it to use SHA-1 algorithm, than feeding it with source data and getting byte array with hash value. To convert this array to hex-string we use our own method convertToHex.

Here is AeSimpleSHA1 class, which single public static method SHA1 returns hexadecimal string representation for SHA1 hash of input argument:

source code: Java
 
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
 
public class AeSimpleSHA1 {
 
    private static String convertToHex(byte[] data) {
        StringBuffer buf = new StringBuffer();
        for (int i = 0; i < data.length; i++) {
            int halfbyte = (data[i] >>> 4) & 0x0F;
            int two_halfs = 0;
            do {
                if ((0 <= halfbyte) && (halfbyte <= 9))
                    buf.append((char) ('0' + halfbyte));
                else
                    buf.append((char) ('a' + (halfbyte - 10)));
                halfbyte = data[i] & 0x0F;
            } while(two_halfs++ < 1);
        }
        return buf.toString();
    }
 
    public static String SHA1(String text) 
    throws NoSuchAlgorithmException, UnsupportedEncodingException  {
    MessageDigest md;
    md = MessageDigest.getInstance("SHA-1");
    byte[] sha1hash = new byte[40];
    md.update(text.getBytes("iso-8859-1"), 0, text.length());
    sha1hash = md.digest();
    return convertToHex(sha1hash);
    }
}
 

You may use this class directly calling this method

source code: Java
 
String sha1_ad1 = AeSimpleSHA1.SHA1("Buy new mobile phone! Nokia, Sony-Ericsson, Samsung, LG, ...");                
String sha1_ad2 = AeSimpleSHA1.SHA1("Buy geek gadgets - iPod, PDA, Notebook");
 

One more example, allows user to input string from console and prints SHA1 hash

source code: Java
 
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;
 
public class Ex01 {
 
    public static void main(String[] args) throws IOException {
        BufferedReader userInput = new BufferedReader (new InputStreamReader(System.in));
 
        System.out.println("Enter string:");
        String rawString = userInput.readLine();
 
        try {
            System.out.println("SHA1 hash of string: " + AeSimpleSHA1.SHA1(rawString));
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}
 
warning 
  • This class is suitable to calculate hash for small chunks of in-memory string data. To process large external files (like ISO images) you should use MessageDigest class directly
  • There may be difficulties while processing string data in encodings other than iso-8859-1.
tested by AnyExample.com on 2006-09-02
  • JDK 1.5
 


 
© AnyExample 2010
License | Privacy | Contact