JavaEnterprise JavaUser Code: Make an SHA Fingerprint from a String

User Code: Make an SHA Fingerprint from a String content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

It’s possible, in an applet, that this code won’t work for
some Netscape Navigator versions, because they don’t have the
MessageDigest class included (perhaps this only concerns European
versions, because of some export restrictions to cryptographic code).

In that case, as far as I know, the only way to implement the SHA
is to follow Steve Reid’s originial C++ code step by step. But
there also exist some Java translations on the Net.

How It Works

You just call makeSHA("Hello World!"), and you’ll get
back a string consisting of the hex-view of the encoded bytes.

import java.lang.*;
import java.util.*;

public class mysha {

 public static String toHexString(byte b)
     int value = (b & 0x7F) + (b < 0 ? 128 : 0);
     String ret = (value < 16 ? "0" : "");
     ret += Integer.toHexString(value).toUpperCase();
     return ret;

 public static String makeSHA(String inputstring) {
 String outputstring="";
  // Objekt mit SHA" holen => initialize SHA object
  MessageDigest md = MessageDigest.getInstance("SHA");

  byte[] myText = inputstring.getBytes();
  // Berechnen => Calculate

  byte[] result = md.digest();
  // Ausgeben => Output
    for (int i = 0; i < result.length; ++i) {
  catch ( Exception e) {
  return outputstring;


 public static void main(String arguments[]) {
  // runs test-vector "abc"



About the Author

Andreas Brandmaier
is a student at the University of Munich, working with statistical
databases using Perl and Java.

Java users are encouraged to submit samples of useful code for publication in the pages of Gamelan. Send your files and comments to for consideration. Thank you.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories