JavaEnterprise JavaUser Code: Make an SHA Fingerprint from a String

User Code: Make an SHA Fingerprint from a String

Developer.com 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.io.*;
import java.lang.*;
import java.security.*;
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="";
 try
 {
  // Objekt mit SHA" holen => initialize SHA object
  MessageDigest md = MessageDigest.getInstance("SHA");

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

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

 }


 public static void main(String arguments[]) {
  // runs test-vector "abc"
  System.out.println(makeSHA("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 editor@developer.com for consideration. Thank you.

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories