Java/Security/Message Digest

Материал из Java эксперт
Перейти к: навигация, поиск

Create a checksum

   
import java.io.FileInputStream;
import java.io.InputStream;
import java.security.MessageDigest;
public class Main {
  public static void main(String args[]) throws Exception {
    InputStream fis = new FileInputStream("a.exe");
    byte[] buffer = new byte[1024];
    MessageDigest complete = MessageDigest.getInstance("MD5");
    int numRead;
    do {
      numRead = fis.read(buffer);
      if (numRead > 0) {
        complete.update(buffer, 0, numRead);
      }
    } while (numRead != -1);
    fis.close();
    
    byte[] b = complete.digest();
    String result = "";
    for (int i = 0; i < b.length; i++) {
      result += Integer.toString((b[i] & 0xff) + 0x100, 16).substring(1);
    }
    System.out.println(result);
  }
}





Digest string

 
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.MessageDigest;
public class Utils {
  public static String digest(String token) throws GeneralSecurityException, IOException {
    MessageDigest sha1 = MessageDigest.getInstance("SHA1");
    return byteArrayToHexStr(sha1.digest(token.getBytes("UTF-8")));
  }
  private static String byteArrayToHexStr(byte[] data) {
    char[] chars = new char[data.length * 2];
    for (int i = 0; i < data.length; i++) {
      byte current = data[i];
      int hi = (current & 0xF0) >> 4;
      int lo = current & 0x0F;
      chars[2 * i] = (char) (hi < 10 ? ("0" + hi) : ("A" + hi - 10));
      chars[2 * i + 1] = (char) (lo < 10 ? ("0" + lo) : ("A" + lo - 10));
    }
    return new String(chars);
  }
}





Implements the MD4 message digest algorithm in Java

  
// This file is currently unlocked (change this line if you lock the file)
//
// $Log: MD4.java,v $
// Revision 1.2  1998/01/05 03:41:19  iang
// Added references only.
//
// Revision 1.1.1.1  1997/11/03 22:36:56  hopwood
// + Imported to CVS (tagged as "start").
//
// Revision 0.1.0.0  1997/07/14  R. Naffah
// + original version
//
// $Endlog$
/*
 * Copyright (c) 1997 Systemics Ltd
 * on behalf of the Cryptix Development Team.  All rights reserved.
 */

import java.security.MessageDigest;
/**
 * Implements the MD4 message digest algorithm in Java.
 * <p>
 * <b>References:</b>
 * <ol>
 *   <li> Ronald L. Rivest,
 *        "",
 *        IETF RFC-1320 (informational).
 * </ol>
 *
 * <p><b>$Revision: 1.2 $</b>
 * @author  Raif S. Naffah
 */
public  class MD4 extends MessageDigest implements Cloneable
{
// MD4 specific object variables
//...........................................................................
    /**
     * The size in bytes of the input block to the tranformation algorithm.
     */
    private static final int BLOCK_LENGTH = 64;       //    = 512 / 8;
    /**
     * 4 32-bit words (interim result)
     */
    private int[] context = new int[4];
    /**
     * Number of bytes processed so far mod. 2 power of 64.
     */
    private long count;
    /**
     * 512 bits input buffer = 16 x 32-bit words holds until reaches 512 bits.
     */
    private byte[] buffer = new byte[BLOCK_LENGTH];
    /**
     * 512 bits work buffer = 16 x 32-bit words
     */
    private int[] X = new int[16];

// Constructors
//...........................................................................
    public MD4 () {
        super("MD4");
        engineReset();
    }
    /**
     *    This constructor is here to implement cloneability of this class.
     */
    private MD4 (MD4 md) {
        this();
        context = (int[])md.context.clone();
        buffer = (byte[])md.buffer.clone();
        count = md.count;
    }

// Cloneable method implementation
//...........................................................................
    /**
     * Returns a copy of this MD object.
     */
    public Object clone() { return new MD4(this); }

// JCE methods
//...........................................................................
    /**
     * Resets this object disregarding any temporary data present at the
     * time of the invocation of this call.
     */
    public void engineReset () {
        // initial values of MD4 i.e. A, B, C, D
        // as per rfc-1320; they are low-order byte first
        context[0] = 0x67452301;
        context[1] = 0xEFCDAB89;
        context[2] = 0x98BADCFE;
        context[3] = 0x10325476;
        count = 0L;
        for (int i = 0; i < BLOCK_LENGTH; i++)
            buffer[i] = 0;
    }
    /**
     * Continues an MD4 message digest using the input byte.
     */
    public void engineUpdate (byte b) {
        // compute number of bytes still unhashed; ie. present in buffer
        int i = (int)(count % BLOCK_LENGTH);
        count++;                                        // update number of bytes
        buffer[i] = b;
        if (i == BLOCK_LENGTH - 1)
            transform(buffer, 0);
    }
    /**
     * MD4 block update operation.
     * <p>
     * Continues an MD4 message digest operation, by filling the buffer,
     * transform(ing) data in 512-bit message block(s), updating the variables
     * context and count, and leaving (buffering) the remaining bytes in buffer
     * for the next update or finish.
     *
     * @param    input    input block
     * @param    offset    start of meaningful bytes in input
     * @param    len        count of bytes in input block to consider
     */
    public void engineUpdate (byte[] input, int offset, int len) {
        // make sure we don"t exceed input"s allocated size/length
        if (offset < 0 || len < 0 || (long)offset + len > input.length)
            throw new ArrayIndexOutOfBoundsException();
        // compute number of bytes still unhashed; ie. present in buffer
        int bufferNdx = (int)(count % BLOCK_LENGTH);
        count += len;                                        // update number of bytes
        int partLen = BLOCK_LENGTH - bufferNdx;
        int i = 0;
        if (len >= partLen) {
            System.arraycopy(input, offset, buffer, bufferNdx, partLen);

            transform(buffer, 0);
            for (i = partLen; i + BLOCK_LENGTH - 1 < len; i+= BLOCK_LENGTH)
                transform(input, offset + i);
            bufferNdx = 0;
        }
        // buffer remaining input
        if (i < len)
            System.arraycopy(input, offset + i, buffer, bufferNdx, len - i);
    }
    /**
     * Completes the hash computation by performing final operations such
     * as padding. At the return of this engineDigest, the MD engine is
     * reset.
     *
     * @return the array of bytes for the resulting hash value.
     */
    public byte[] engineDigest () {
        // pad output to 56 mod 64; as RFC1320 puts it: congruent to 448 mod 512
        int bufferNdx = (int)(count % BLOCK_LENGTH);
        int padLen = (bufferNdx < 56) ? (56 - bufferNdx) : (120 - bufferNdx);
        // padding is alwas binary 1 followed by binary 0s
        byte[] tail = new byte[padLen + 8];
        tail[0] = (byte)0x80;
        // append length before final transform:
        // save number of bits, casting the long to an array of 8 bytes
        // save low-order byte first.
        for (int i = 0; i < 8; i++)
            tail[padLen + i] = (byte)((count * 8) >>> (8 * i));
        engineUpdate(tail, 0, tail.length);
        byte[] result = new byte[16];
        // cast this MD4"s context (array of 4 ints) into an array of 16 bytes.
        for (int i = 0; i < 4; i++)
            for (int j = 0; j < 4; j++)
                result[i * 4 + j] = (byte)(context[i] >>> (8 * j));
        // reset the engine
        engineReset();
        return result;
    }

// own methods
//...........................................................................
    /**
     *    MD4 basic transformation.
     *    <p>
     *    Transforms context based on 512 bits from input block starting
     *    from the offset"th byte.
     *
     *    @param    block    input sub-array.
     *    @param    offset    starting position of sub-array.
     */
    private void transform (byte[] block, int offset) {
        // encodes 64 bytes from input block into an array of 16 32-bit
        // entities. Use A as a temp var.
        for (int i = 0; i < 16; i++)
            X[i] = (block[offset++] & 0xFF)       |
                   (block[offset++] & 0xFF) <<  8 |
                   (block[offset++] & 0xFF) << 16 |
                   (block[offset++] & 0xFF) << 24;

        int A = context[0];
        int B = context[1];
        int C = context[2];
        int D = context[3];
        A = FF(A, B, C, D, X[ 0],  3);
        D = FF(D, A, B, C, X[ 1],  7);
        C = FF(C, D, A, B, X[ 2], 11);
        B = FF(B, C, D, A, X[ 3], 19);
        A = FF(A, B, C, D, X[ 4],  3);
        D = FF(D, A, B, C, X[ 5],  7);
        C = FF(C, D, A, B, X[ 6], 11);
        B = FF(B, C, D, A, X[ 7], 19);
        A = FF(A, B, C, D, X[ 8],  3);
        D = FF(D, A, B, C, X[ 9],  7);
        C = FF(C, D, A, B, X[10], 11);
        B = FF(B, C, D, A, X[11], 19);
        A = FF(A, B, C, D, X[12],  3);
        D = FF(D, A, B, C, X[13],  7);
        C = FF(C, D, A, B, X[14], 11);
        B = FF(B, C, D, A, X[15], 19);
        A = GG(A, B, C, D, X[ 0],  3);
        D = GG(D, A, B, C, X[ 4],  5);
        C = GG(C, D, A, B, X[ 8],  9);
        B = GG(B, C, D, A, X[12], 13);
        A = GG(A, B, C, D, X[ 1],  3);
        D = GG(D, A, B, C, X[ 5],  5);
        C = GG(C, D, A, B, X[ 9],  9);
        B = GG(B, C, D, A, X[13], 13);
        A = GG(A, B, C, D, X[ 2],  3);
        D = GG(D, A, B, C, X[ 6],  5);
        C = GG(C, D, A, B, X[10],  9);
        B = GG(B, C, D, A, X[14], 13);
        A = GG(A, B, C, D, X[ 3],  3);
        D = GG(D, A, B, C, X[ 7],  5);
        C = GG(C, D, A, B, X[11],  9);
        B = GG(B, C, D, A, X[15], 13);
        A = HH(A, B, C, D, X[ 0],  3);
        D = HH(D, A, B, C, X[ 8],  9);
        C = HH(C, D, A, B, X[ 4], 11);
        B = HH(B, C, D, A, X[12], 15);
        A = HH(A, B, C, D, X[ 2],  3);
        D = HH(D, A, B, C, X[10],  9);
        C = HH(C, D, A, B, X[ 6], 11);
        B = HH(B, C, D, A, X[14], 15);
        A = HH(A, B, C, D, X[ 1],  3);
        D = HH(D, A, B, C, X[ 9],  9);
        C = HH(C, D, A, B, X[ 5], 11);
        B = HH(B, C, D, A, X[13], 15);
        A = HH(A, B, C, D, X[ 3],  3);
        D = HH(D, A, B, C, X[11],  9);
        C = HH(C, D, A, B, X[ 7], 11);
        B = HH(B, C, D, A, X[15], 15);
        context[0] += A;
        context[1] += B;
        context[2] += C;
        context[3] += D;
    }
    // The basic MD4 atomic functions.
    private int FF (int a, int b, int c, int d, int x, int s) {
        int t = a + ((b & c) | (~b & d)) + x;
        return t << s | t >>> (32 - s);
    }
    private int GG (int a, int b, int c, int d, int x, int s) {
        int t = a + ((b & (c | d)) | (c & d)) + x + 0x5A827999;
        return t << s | t >>> (32 - s);
    }
    private int HH (int a, int b, int c, int d, int x, int s) {
        int t = a + (b ^ c ^ d) + x + 0x6ED9EBA1;
        return t << s | t >>> (32 - s);
    }
}





MD4 Digest

 

/******************************************************************************
 * Copyright (c) 2000 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 ******************************************************************************/

/**
 * implementation of MD4 as RFC 1320 by R. Rivest, MIT Laboratory for
 * Computer Science and RSA Data Security, Inc.
 * <p>
 * <b>NOTE</b>: This algorithm is only included for backwards compatability
 * with legacy applications, it"s not secure, don"t use it for anything new!
 *
 * @version $Id: MD4Digest.java,v 1.2 2004/06/27 17:00:55 bheineman Exp $
 */
public class MD4Digest extends GeneralDigest {
    private static final int DIGEST_LENGTH = 16;
    //
    // round 1 left rotates
    //
    private static final int S11 = 3;
    private static final int S12 = 7;
    private static final int S13 = 11;
    private static final int S14 = 19;
    //
    // round 2 left rotates
    //
    private static final int S21 = 3;
    private static final int S22 = 5;
    private static final int S23 = 9;
    private static final int S24 = 13;
    //
    // round 3 left rotates
    //
    private static final int S31 = 3;
    private static final int S32 = 9;
    private static final int S33 = 11;
    private static final int S34 = 15;
    private int H1, H2, H3, H4;         // IV"s
    private int[] X = new int[16];
    private int xOff;
    /**
     * Standard constructor
     */
    public MD4Digest() {
        reset();
    }
    /**
     * Copy constructor.  This will copy the state of the provided
     * message digest.
     */
    public MD4Digest(MD4Digest t) {
        super(t);
        H1 = t.H1;
        H2 = t.H2;
        H3 = t.H3;
        H4 = t.H4;
        System.arraycopy(t.X, 0, X, 0, t.X.length);
        xOff = t.xOff;
    }
    public String getAlgorithmName() {
        return "MD4";
    }
    public int getDigestSize() {
        return DIGEST_LENGTH;
    }
    protected void processWord(byte[] in, int inOff) {
        X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8)
                    | ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24);
        if (xOff == 16) {
            processBlock();
        }
    }
    protected void processLength(long bitLength) {
        if (xOff > 14) {
            processBlock();
        }
        X[14] = (int)(bitLength & 0xffffffff);
        X[15] = (int)(bitLength >>> 32);
    }
    private void unpackWord(int word, byte[] out, int outOff) {
        out[outOff]     = (byte)word;
        out[outOff + 1] = (byte)(word >>> 8);
        out[outOff + 2] = (byte)(word >>> 16);
        out[outOff + 3] = (byte)(word >>> 24);
    }
    public int doFinal(byte[] out, int outOff) {
        finish();
        unpackWord(H1, out, outOff);
        unpackWord(H2, out, outOff + 4);
        unpackWord(H3, out, outOff + 8);
        unpackWord(H4, out, outOff + 12);
        reset();
        return DIGEST_LENGTH;
    }
    /**
     * reset the chaining variables to the IV values.
     */
    public void reset() {
        super.reset();
        H1 = 0x67452301;
        H2 = 0xefcdab89;
        H3 = 0x98badcfe;
        H4 = 0x10325476;
        xOff = 0;
        for (int i = 0; i != X.length; i++) {
            X[i] = 0;
        }
    }
    /*
     * rotate int x left n bits.
     */
    private int rotateLeft(int x, int n) {
        return(x << n) | (x >>> (32 - n));
    }
    /*
     * F, G, H and I are the basic MD4 functions.
     */
    private int F(int u, int v, int w) {
        return(u & v) | (~u & w);
    }
    private int G(int u, int v, int w) {
        return(u & v) | (u & w) | (v & w);
    }
    private int H(int u, int v, int w) {
        return u ^ v ^ w;
    }
    protected void processBlock() {
        int a = H1;
        int b = H2;
        int c = H3;
        int d = H4;
        //
        // Round 1 - F cycle, 16 times.
        //
        a = rotateLeft((a + F(b, c, d) + X[ 0]), S11);
        d = rotateLeft((d + F(a, b, c) + X[ 1]), S12);
        c = rotateLeft((c + F(d, a, b) + X[ 2]), S13);
        b = rotateLeft((b + F(c, d, a) + X[ 3]), S14);
        a = rotateLeft((a + F(b, c, d) + X[ 4]), S11);
        d = rotateLeft((d + F(a, b, c) + X[ 5]), S12);
        c = rotateLeft((c + F(d, a, b) + X[ 6]), S13);
        b = rotateLeft((b + F(c, d, a) + X[ 7]), S14);
        a = rotateLeft((a + F(b, c, d) + X[ 8]), S11);
        d = rotateLeft((d + F(a, b, c) + X[ 9]), S12);
        c = rotateLeft((c + F(d, a, b) + X[10]), S13);
        b = rotateLeft((b + F(c, d, a) + X[11]), S14);
        a = rotateLeft((a + F(b, c, d) + X[12]), S11);
        d = rotateLeft((d + F(a, b, c) + X[13]), S12);
        c = rotateLeft((c + F(d, a, b) + X[14]), S13);
        b = rotateLeft((b + F(c, d, a) + X[15]), S14);
        //
        // Round 2 - G cycle, 16 times.
        //
        a = rotateLeft((a + G(b, c, d) + X[ 0] + 0x5a827999), S21);
        d = rotateLeft((d + G(a, b, c) + X[ 4] + 0x5a827999), S22);
        c = rotateLeft((c + G(d, a, b) + X[ 8] + 0x5a827999), S23);
        b = rotateLeft((b + G(c, d, a) + X[12] + 0x5a827999), S24);
        a = rotateLeft((a + G(b, c, d) + X[ 1] + 0x5a827999), S21);
        d = rotateLeft((d + G(a, b, c) + X[ 5] + 0x5a827999), S22);
        c = rotateLeft((c + G(d, a, b) + X[ 9] + 0x5a827999), S23);
        b = rotateLeft((b + G(c, d, a) + X[13] + 0x5a827999), S24);
        a = rotateLeft((a + G(b, c, d) + X[ 2] + 0x5a827999), S21);
        d = rotateLeft((d + G(a, b, c) + X[ 6] + 0x5a827999), S22);
        c = rotateLeft((c + G(d, a, b) + X[10] + 0x5a827999), S23);
        b = rotateLeft((b + G(c, d, a) + X[14] + 0x5a827999), S24);
        a = rotateLeft((a + G(b, c, d) + X[ 3] + 0x5a827999), S21);
        d = rotateLeft((d + G(a, b, c) + X[ 7] + 0x5a827999), S22);
        c = rotateLeft((c + G(d, a, b) + X[11] + 0x5a827999), S23);
        b = rotateLeft((b + G(c, d, a) + X[15] + 0x5a827999), S24);
        //
        // Round 3 - H cycle, 16 times.
        //
        a = rotateLeft((a + H(b, c, d) + X[ 0] + 0x6ed9eba1), S31);
        d = rotateLeft((d + H(a, b, c) + X[ 8] + 0x6ed9eba1), S32);
        c = rotateLeft((c + H(d, a, b) + X[ 4] + 0x6ed9eba1), S33);
        b = rotateLeft((b + H(c, d, a) + X[12] + 0x6ed9eba1), S34);
        a = rotateLeft((a + H(b, c, d) + X[ 2] + 0x6ed9eba1), S31);
        d = rotateLeft((d + H(a, b, c) + X[10] + 0x6ed9eba1), S32);
        c = rotateLeft((c + H(d, a, b) + X[ 6] + 0x6ed9eba1), S33);
        b = rotateLeft((b + H(c, d, a) + X[14] + 0x6ed9eba1), S34);
        a = rotateLeft((a + H(b, c, d) + X[ 1] + 0x6ed9eba1), S31);
        d = rotateLeft((d + H(a, b, c) + X[ 9] + 0x6ed9eba1), S32);
        c = rotateLeft((c + H(d, a, b) + X[ 5] + 0x6ed9eba1), S33);
        b = rotateLeft((b + H(c, d, a) + X[13] + 0x6ed9eba1), S34);
        a = rotateLeft((a + H(b, c, d) + X[ 3] + 0x6ed9eba1), S31);
        d = rotateLeft((d + H(a, b, c) + X[11] + 0x6ed9eba1), S32);
        c = rotateLeft((c + H(d, a, b) + X[ 7] + 0x6ed9eba1), S33);
        b = rotateLeft((b + H(c, d, a) + X[15] + 0x6ed9eba1), S34);
        H1 += a;
        H2 += b;
        H3 += c;
        H4 += d;
        //
        // reset the offset and clean out the word buffer.
        //
        xOff = 0;
        for (int i = 0; i != X.length; i++) {
            X[i] = 0;
        }
    }
}
/**
 * base implementation of MD4 family style digest as outlined in
 * "Handbook of Applied Cryptography", pages 344 - 347.
 *
 * @version $Id: GeneralDigest.java,v 1.2 2004/06/27 17:00:55 bheineman Exp $
 */
abstract class GeneralDigest
//    implements Digest - mdb: we don"t care about this interface
{
    private byte[]  xBuf;
    private int     xBufOff;
    private long    byteCount;
  /**
   * Standard constructor
   */
  protected GeneralDigest()
  {
    xBuf = new byte[4];
    xBufOff = 0;
  }
  /**
   * Copy constructor.  We are using copy constructors in place
   * of the Object.clone() interface as this interface is not
   * supported by J2ME.
   */
  protected GeneralDigest(GeneralDigest t)
  {
        xBuf = new byte[t.xBuf.length];
    System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
    xBufOff = t.xBufOff;
    byteCount = t.byteCount;
  }
    public void update(
        byte in)
    {
        xBuf[xBufOff++] = in;
        if (xBufOff == xBuf.length)
        {
            processWord(xBuf, 0);
            xBufOff = 0;
        }
        byteCount++;
    }
    public void update(
        byte[]  in,
        int     inOff,
        int     len)
    {
        //
        // fill the current word
        //
        while ((xBufOff != 0) && (len > 0))
        {
            update(in[inOff]);
            inOff++;
            len--;
        }
        //
        // process whole words.
        //
        while (len > xBuf.length)
        {
            processWord(in, inOff);
            inOff += xBuf.length;
            len -= xBuf.length;
            byteCount += xBuf.length;
        }
        //
        // load in the remainder.
        //
        while (len > 0)
        {
            update(in[inOff]);
            inOff++;
            len--;
        }
    }
    public void finish()
    {
        long    bitLength = (byteCount << 3);
        //
        // add the pad bytes.
        //
        update((byte)128);
        while (xBufOff != 0)
        {
            update((byte)0);
        }
        processLength(bitLength);
        processBlock();
    }
    public void reset()
    {
        byteCount = 0;
        xBufOff = 0;
    for ( int i = 0; i < xBuf.length; i++ ) {
      xBuf[i] = 0;
    }
    }
    protected abstract void processWord(byte[] in, int inOff);
    protected abstract void processLength(long bitLength);
    protected abstract void processBlock();
}





MD5 Digest

 
/******************************************************************************
 * Copyright (c) 2000 The Legion Of The Bouncy Castle (http://www.bouncycastle.org)
 * Permission is hereby granted, free of charge, to any person obtaining a
 * copy of this software and associated documentation files (the "Software"),
 * to deal in the Software without restriction, including without limitation
 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
 * and/or sell copies of the Software, and to permit persons to whom the
 * Software is furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included
 * in all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
 * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
 * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
 * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM,
 * DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR
 * OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE
 * USE OR OTHER DEALINGS IN THE SOFTWARE.
 ******************************************************************************/

/**
 * implementation of MD5 as outlined in "Handbook of Applied Cryptography", pages 346 - 347.
 */
public class MD5Digest
    extends GeneralDigest
{
    private static final int    DIGEST_LENGTH = 16;
    private int     H1, H2, H3, H4;         // IV"s
    private int[]   X = new int[16];
    private int     xOff;
    /**
     * Standard constructor
     */
    public MD5Digest()
    {
        reset();
    }
    /**
     * Copy constructor.  This will copy the state of the provided
     * message digest.
     */
    public MD5Digest(MD5Digest t)
    {
        super(t);
        H1 = t.H1;
        H2 = t.H2;
        H3 = t.H3;
        H4 = t.H4;
        System.arraycopy(t.X, 0, X, 0, t.X.length);
        xOff = t.xOff;
    }
    public String getAlgorithmName()
    {
        return "MD5";
    }
    public int getDigestSize()
    {
        return DIGEST_LENGTH;
    }
    protected void processWord(
        byte[]  in,
        int     inOff)
    {
        X[xOff++] = (in[inOff] & 0xff) | ((in[inOff + 1] & 0xff) << 8)
            | ((in[inOff + 2] & 0xff) << 16) | ((in[inOff + 3] & 0xff) << 24); 
        if (xOff == 16)
        {
            processBlock();
        }
    }
    protected void processLength(
        long    bitLength)
    {
        if (xOff > 14)
        {
            processBlock();
        }
        X[14] = (int)(bitLength & 0xffffffff);
        X[15] = (int)(bitLength >>> 32);
    }
    private void unpackWord(
        int     word,
        byte[]  out,
        int     outOff)
    {
        out[outOff]     = (byte)word;
        out[outOff + 1] = (byte)(word >>> 8);
        out[outOff + 2] = (byte)(word >>> 16);
        out[outOff + 3] = (byte)(word >>> 24);
    }
    public int doFinal(
        byte[]  out,
        int     outOff)
    {
        finish();
        unpackWord(H1, out, outOff);
        unpackWord(H2, out, outOff + 4);
        unpackWord(H3, out, outOff + 8);
        unpackWord(H4, out, outOff + 12);
        reset();
        return DIGEST_LENGTH;
    }
    /**
     * reset the chaining variables to the IV values.
     */
    public void reset()
    {
        super.reset();
        H1 = 0x67452301;
        H2 = 0xefcdab89;
        H3 = 0x98badcfe;
        H4 = 0x10325476;
        xOff = 0;
        for (int i = 0; i != X.length; i++)
        {
            X[i] = 0;
        }
    }
    //
    // round 1 left rotates
    //
    private static final int S11 = 7;
    private static final int S12 = 12;
    private static final int S13 = 17;
    private static final int S14 = 22;
    //
    // round 2 left rotates
    //
    private static final int S21 = 5;
    private static final int S22 = 9;
    private static final int S23 = 14;
    private static final int S24 = 20;
    //
    // round 3 left rotates
    //
    private static final int S31 = 4;
    private static final int S32 = 11;
    private static final int S33 = 16;
    private static final int S34 = 23;
    //
    // round 4 left rotates
    //
    private static final int S41 = 6;
    private static final int S42 = 10;
    private static final int S43 = 15;
    private static final int S44 = 21;
    /*
     * rotate int x left n bits.
     */
    private int rotateLeft(
        int x,
        int n)
    {
        return (x << n) | (x >>> (32 - n));
    }
    /*
     * F, G, H and I are the basic MD5 functions.
     */
    private int F(
        int u,
        int v,
        int w)
    {
        return (u & v) | (~u & w);
    }
    private int G(
        int u,
        int v,
        int w)
    {
        return (u & w) | (v & ~w);
    }
    private int H(
        int u,
        int v,
        int w)
    {
        return u ^ v ^ w;
    }
    private int K(
        int u,
        int v,
        int w)
    {
        return v ^ (u | ~w);
    }
    protected void processBlock()
    {
        int a = H1;
        int b = H2;
        int c = H3;
        int d = H4;
        //
        // Round 1 - F cycle, 16 times.
        //
        a = rotateLeft(a + F(b, c, d) + X[ 0] + 0xd76aa478, S11) + b;
        d = rotateLeft(d + F(a, b, c) + X[ 1] + 0xe8c7b756, S12) + a;
        c = rotateLeft(c + F(d, a, b) + X[ 2] + 0x242070db, S13) + d;
        b = rotateLeft(b + F(c, d, a) + X[ 3] + 0xc1bdceee, S14) + c;
        a = rotateLeft(a + F(b, c, d) + X[ 4] + 0xf57c0faf, S11) + b;
        d = rotateLeft(d + F(a, b, c) + X[ 5] + 0x4787c62a, S12) + a;
        c = rotateLeft(c + F(d, a, b) + X[ 6] + 0xa8304613, S13) + d;
        b = rotateLeft(b + F(c, d, a) + X[ 7] + 0xfd469501, S14) + c;
        a = rotateLeft(a + F(b, c, d) + X[ 8] + 0x698098d8, S11) + b;
        d = rotateLeft(d + F(a, b, c) + X[ 9] + 0x8b44f7af, S12) + a;
        c = rotateLeft(c + F(d, a, b) + X[10] + 0xffff5bb1, S13) + d;
        b = rotateLeft(b + F(c, d, a) + X[11] + 0x895cd7be, S14) + c;
        a = rotateLeft(a + F(b, c, d) + X[12] + 0x6b901122, S11) + b;
        d = rotateLeft(d + F(a, b, c) + X[13] + 0xfd987193, S12) + a;
        c = rotateLeft(c + F(d, a, b) + X[14] + 0xa679438e, S13) + d;
        b = rotateLeft(b + F(c, d, a) + X[15] + 0x49b40821, S14) + c;
        //
        // Round 2 - G cycle, 16 times.
        //
        a = rotateLeft(a + G(b, c, d) + X[ 1] + 0xf61e2562, S21) + b;
        d = rotateLeft(d + G(a, b, c) + X[ 6] + 0xc040b340, S22) + a;
        c = rotateLeft(c + G(d, a, b) + X[11] + 0x265e5a51, S23) + d;
        b = rotateLeft(b + G(c, d, a) + X[ 0] + 0xe9b6c7aa, S24) + c;
        a = rotateLeft(a + G(b, c, d) + X[ 5] + 0xd62f105d, S21) + b;
        d = rotateLeft(d + G(a, b, c) + X[10] + 0x02441453, S22) + a;
        c = rotateLeft(c + G(d, a, b) + X[15] + 0xd8a1e681, S23) + d;
        b = rotateLeft(b + G(c, d, a) + X[ 4] + 0xe7d3fbc8, S24) + c;
        a = rotateLeft(a + G(b, c, d) + X[ 9] + 0x21e1cde6, S21) + b;
        d = rotateLeft(d + G(a, b, c) + X[14] + 0xc33707d6, S22) + a;
        c = rotateLeft(c + G(d, a, b) + X[ 3] + 0xf4d50d87, S23) + d;
        b = rotateLeft(b + G(c, d, a) + X[ 8] + 0x455a14ed, S24) + c;
        a = rotateLeft(a + G(b, c, d) + X[13] + 0xa9e3e905, S21) + b;
        d = rotateLeft(d + G(a, b, c) + X[ 2] + 0xfcefa3f8, S22) + a;
        c = rotateLeft(c + G(d, a, b) + X[ 7] + 0x676f02d9, S23) + d;
        b = rotateLeft(b + G(c, d, a) + X[12] + 0x8d2a4c8a, S24) + c;
        //
        // Round 3 - H cycle, 16 times.
        //
        a = rotateLeft(a + H(b, c, d) + X[ 5] + 0xfffa3942, S31) + b;
        d = rotateLeft(d + H(a, b, c) + X[ 8] + 0x8771f681, S32) + a;
        c = rotateLeft(c + H(d, a, b) + X[11] + 0x6d9d6122, S33) + d;
        b = rotateLeft(b + H(c, d, a) + X[14] + 0xfde5380c, S34) + c;
        a = rotateLeft(a + H(b, c, d) + X[ 1] + 0xa4beea44, S31) + b;
        d = rotateLeft(d + H(a, b, c) + X[ 4] + 0x4bdecfa9, S32) + a;
        c = rotateLeft(c + H(d, a, b) + X[ 7] + 0xf6bb4b60, S33) + d;
        b = rotateLeft(b + H(c, d, a) + X[10] + 0xbebfbc70, S34) + c;
        a = rotateLeft(a + H(b, c, d) + X[13] + 0x289b7ec6, S31) + b;
        d = rotateLeft(d + H(a, b, c) + X[ 0] + 0xeaa127fa, S32) + a;
        c = rotateLeft(c + H(d, a, b) + X[ 3] + 0xd4ef3085, S33) + d;
        b = rotateLeft(b + H(c, d, a) + X[ 6] + 0x04881d05, S34) + c;
        a = rotateLeft(a + H(b, c, d) + X[ 9] + 0xd9d4d039, S31) + b;
        d = rotateLeft(d + H(a, b, c) + X[12] + 0xe6db99e5, S32) + a;
        c = rotateLeft(c + H(d, a, b) + X[15] + 0x1fa27cf8, S33) + d;
        b = rotateLeft(b + H(c, d, a) + X[ 2] + 0xc4ac5665, S34) + c;
        //
        // Round 4 - K cycle, 16 times.
        //
        a = rotateLeft(a + K(b, c, d) + X[ 0] + 0xf4292244, S41) + b;
        d = rotateLeft(d + K(a, b, c) + X[ 7] + 0x432aff97, S42) + a;
        c = rotateLeft(c + K(d, a, b) + X[14] + 0xab9423a7, S43) + d;
        b = rotateLeft(b + K(c, d, a) + X[ 5] + 0xfc93a039, S44) + c;
        a = rotateLeft(a + K(b, c, d) + X[12] + 0x655b59c3, S41) + b;
        d = rotateLeft(d + K(a, b, c) + X[ 3] + 0x8f0ccc92, S42) + a;
        c = rotateLeft(c + K(d, a, b) + X[10] + 0xffeff47d, S43) + d;
        b = rotateLeft(b + K(c, d, a) + X[ 1] + 0x85845dd1, S44) + c;
        a = rotateLeft(a + K(b, c, d) + X[ 8] + 0x6fa87e4f, S41) + b;
        d = rotateLeft(d + K(a, b, c) + X[15] + 0xfe2ce6e0, S42) + a;
        c = rotateLeft(c + K(d, a, b) + X[ 6] + 0xa3014314, S43) + d;
        b = rotateLeft(b + K(c, d, a) + X[13] + 0x4e0811a1, S44) + c;
        a = rotateLeft(a + K(b, c, d) + X[ 4] + 0xf7537e82, S41) + b;
        d = rotateLeft(d + K(a, b, c) + X[11] + 0xbd3af235, S42) + a;
        c = rotateLeft(c + K(d, a, b) + X[ 2] + 0x2ad7d2bb, S43) + d;
        b = rotateLeft(b + K(c, d, a) + X[ 9] + 0xeb86d391, S44) + c;
        H1 += a;
        H2 += b;
        H3 += c;
        H4 += d;
        //
        // reset the offset and clean out the word buffer.
        //
        xOff = 0;
        for (int i = 0; i != X.length; i++)
        {
            X[i] = 0;
        }
    }
}
/**
 * base implementation of MD4 family style digest as outlined in
 * "Handbook of Applied Cryptography", pages 344 - 347.
 *
 * @version $Id: GeneralDigest.java,v 1.2 2004/06/27 17:00:55 bheineman Exp $
 */
abstract class GeneralDigest
//    implements Digest - mdb: we don"t care about this interface
{
    private byte[]  xBuf;
    private int     xBufOff;
    private long    byteCount;
  /**
   * Standard constructor
   */
  protected GeneralDigest()
  {
    xBuf = new byte[4];
    xBufOff = 0;
  }
  /**
   * Copy constructor.  We are using copy constructors in place
   * of the Object.clone() interface as this interface is not
   * supported by J2ME.
   */
  protected GeneralDigest(GeneralDigest t)
  {
        xBuf = new byte[t.xBuf.length];
    System.arraycopy(t.xBuf, 0, xBuf, 0, t.xBuf.length);
    xBufOff = t.xBufOff;
    byteCount = t.byteCount;
  }
    public void update(
        byte in)
    {
        xBuf[xBufOff++] = in;
        if (xBufOff == xBuf.length)
        {
            processWord(xBuf, 0);
            xBufOff = 0;
        }
        byteCount++;
    }
    public void update(
        byte[]  in,
        int     inOff,
        int     len)
    {
        //
        // fill the current word
        //
        while ((xBufOff != 0) && (len > 0))
        {
            update(in[inOff]);
            inOff++;
            len--;
        }
        //
        // process whole words.
        //
        while (len > xBuf.length)
        {
            processWord(in, inOff);
            inOff += xBuf.length;
            len -= xBuf.length;
            byteCount += xBuf.length;
        }
        //
        // load in the remainder.
        //
        while (len > 0)
        {
            update(in[inOff]);
            inOff++;
            len--;
        }
    }
    public void finish()
    {
        long    bitLength = (byteCount << 3);
        //
        // add the pad bytes.
        //
        update((byte)128);
        while (xBufOff != 0)
        {
            update((byte)0);
        }
        processLength(bitLength);
        processBlock();
    }
    public void reset()
    {
        byteCount = 0;
        xBufOff = 0;
    for ( int i = 0; i < xBuf.length; i++ ) {
      xBuf[i] = 0;
    }
    }
    protected abstract void processWord(byte[] in, int inOff);
    protected abstract void processLength(long bitLength);
    protected abstract void processBlock();
}





MessageDigest with SHA-1

  
import java.security.MessageDigest;
import java.security.Security;
public class MainClass {
  public static void main(String args[]) throws Exception {
    Security.addProvider(new org.bouncycastle.jce.provider.BouncyCastleProvider());
    MessageDigest sha = MessageDigest.getInstance("SHA-1");
    byte[] data1 = {65,66,67,68,69};
    sha.update(data1);
    byte[] msgDigest = sha.digest();
    System.out.println("--- Message Digest ---");
    for(int i=0; i<msgDigest.length; i++) {
        System.out.print(msgDigest[i] + " ");
    }
  }
}





Operations to simplifiy common java.security.MessageDigest tasks.

 
/*
 * Copyright 2001-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 * 
 *      http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
/**
 * Operations to simplifiy common {@link java.security.MessageDigest} tasks.
 * This class is thread safe.
 * 
 * @author Apache Software Foundation
 */
public class DigestUtils {
  /**
   * Returns a MessageDigest for the given <code>algorithm</code>.
   * 
   * @param algorithm
   *          The MessageDigest algorithm name.
   * @return An MD5 digest instance.
   * @throws RuntimeException
   *           when a {@link java.security.NoSuchAlgorithmException} is caught,
   */
  static MessageDigest getDigest(String algorithm) {
    try {
      return MessageDigest.getInstance(algorithm);
    } catch (NoSuchAlgorithmException e) {
      throw new RuntimeException(e.getMessage());
    }
  }
  /**
   * Returns an MD5 MessageDigest.
   * 
   * @return An MD5 digest instance.
   * @throws RuntimeException
   *           when a {@link java.security.NoSuchAlgorithmException} is caught,
   */
  private static MessageDigest getMd5Digest() {
    return getDigest("MD5");
  }
  /**
   * Returns an SHA digest.
   * 
   * @return An SHA digest instance.
   * @throws RuntimeException
   *           when a {@link java.security.NoSuchAlgorithmException} is caught,
   */
  private static MessageDigest getShaDigest() {
    return getDigest("SHA");
  }
  /**
   * Calculates the MD5 digest and returns the value as a 16 element
   * <code>byte[]</code>.
   * 
   * @param data
   *          Data to digest
   * @return MD5 digest
   */
  public static byte[] md5(byte[] data) {
    return getMd5Digest().digest(data);
  }
  /**
   * Calculates the MD5 digest and returns the value as a 16 element
   * <code>byte[]</code>.
   * 
   * @param data
   *          Data to digest
   * @return MD5 digest
   */
  public static byte[] md5(String data) {
    return md5(data.getBytes());
  }
  /**
   * Calculates the MD5 digest and returns the value as a 32 character hex
   * string.
   * 
   * @param data
   *          Data to digest
   * @return MD5 digest as a hex string
   */
  public static String md5Hex(byte[] data) {
    return new String(Hex.encodeHex(md5(data)));
  }
  /**
   * Calculates the MD5 digest and returns the value as a 32 character hex
   * string.
   * 
   * @param data
   *          Data to digest
   * @return MD5 digest as a hex string
   */
  public static String md5Hex(String data) {
    return new String(Hex.encodeHex(md5(data)));
  }
  /**
   * Calculates the SHA digest and returns the value as a <code>byte[]</code>.
   * 
   * @param data
   *          Data to digest
   * @return SHA digest
   */
  public static byte[] sha(byte[] data) {
    return getShaDigest().digest(data);
  }
  /**
   * Calculates the SHA digest and returns the value as a <code>byte[]</code>.
   * 
   * @param data
   *          Data to digest
   * @return SHA digest
   */
  public static byte[] sha(String data) {
    return sha(data.getBytes());
  }
  /**
   * Calculates the SHA digest and returns the value as a hex string.
   * 
   * @param data
   *          Data to digest
   * @return SHA digest as a hex string
   */
  public static String shaHex(byte[] data) {
    return new String(Hex.encodeHex(sha(data)));
  }
  /**
   * Calculates the SHA digest and returns the value as a hex string.
   * 
   * @param data
   *          Data to digest
   * @return SHA digest as a hex string
   */
  public static String shaHex(String data) {
    return new String(Hex.encodeHex(sha(data)));
  }
}
/*
 * Copyright 2001-2004 The Apache Software Foundation.
 * 
 * Licensed under the Apache License, Version 2.0 (the "License"); you may not
 * use this file except in compliance with the License. You may obtain a copy of
 * the License at
 * 
 * http://www.apache.org/licenses/LICENSE-2.0
 * 
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
 * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
 * License for the specific language governing permissions and limitations under
 * the License.
 */
/**
 * Hex encoder and decoder.
 * 
 * @since 1.1
 * @author Apache Software Foundation
 * @version $Id: Hex.java,v 1.13 2004/04/18 18:22:33 ggregory Exp $
 */
class Hex {
  /**
   * Used building output as Hex
   */
  private static final char[] DIGITS = { "0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a",
      "b", "c", "d", "e", "f" };
  /**
   * Converts an array of characters representing hexidecimal values into an
   * array of bytes of those same values. The returned array will be half the
   * length of the passed array, as it takes two characters to represent any
   * given byte. An exception is thrown if the passed char array has an odd
   * number of elements.
   * 
   * @param data
   *          An array of characters containing hexidecimal digits
   * @return A byte array containing binary data decoded from the supplied char
   *         array.
   * @throws DecoderException
   *           Thrown if an odd number or illegal of characters is supplied
   */
  public static byte[] decodeHex(char[] data) throws RuntimeException {
    int len = data.length;
    if ((len & 0x01) != 0) {
      throw new RuntimeException("Odd number of characters.");
    }
    byte[] out = new byte[len >> 1];
    // two characters form the hex value.
    for (int i = 0, j = 0; j < len; i++) {
      int f = toDigit(data[j], j) << 4;
      j++;
      f = f | toDigit(data[j], j);
      j++;
      out[i] = (byte) (f & 0xFF);
    }
    return out;
  }
  /**
   * Converts a hexadecimal character to an integer.
   * 
   * @param ch
   *          A character to convert to an integer digit
   * @param index
   *          The index of the character in the source
   * @return An integer
   * @throws DecoderException
   *           Thrown if ch is an illegal hex character
   */
  protected static int toDigit(char ch, int index) throws RuntimeException {
    int digit = Character.digit(ch, 16);
    if (digit == -1) {
      throw new RuntimeException("Illegal hexadecimal charcter " + ch + " at index " + index);
    }
    return digit;
  }
  /**
   * Converts an array of bytes into an array of characters representing the
   * hexidecimal values of each byte in order. The returned array will be double
   * the length of the passed array, as it takes two characters to represent any
   * given byte.
   * 
   * @param data
   *          a byte[] to convert to Hex characters
   * @return A char[] containing hexidecimal characters
   */
  public static char[] encodeHex(byte[] data) {
    int l = data.length;
    char[] out = new char[l << 1];
    // two characters form the hex value.
    for (int i = 0, j = 0; i < l; i++) {
      out[j++] = DIGITS[(0xF0 & data[i]) >>> 4];
      out[j++] = DIGITS[0x0F & data[i]];
    }
    return out;
  }
  /**
   * Converts an array of character bytes representing hexidecimal values into
   * an array of bytes of those same values. The returned array will be half the
   * length of the passed array, as it takes two characters to represent any
   * given byte. An exception is thrown if the passed char array has an odd
   * number of elements.
   * 
   * @param array
   *          An array of character bytes containing hexidecimal digits
   * @return A byte array containing binary data decoded from the supplied byte
   *         array (representing characters).
   * @throws DecoderException
   *           Thrown if an odd number of characters is supplied to this
   *           function
   * @see #decodeHex(char[])
   */
  public byte[] decode(byte[] array) throws RuntimeException {
    return decodeHex(new String(array).toCharArray());
  }
  /**
   * Converts a String or an array of character bytes representing hexidecimal
   * values into an array of bytes of those same values. The returned array will
   * be half the length of the passed String or array, as it takes two
   * characters to represent any given byte. An exception is thrown if the
   * passed char array has an odd number of elements.
   * 
   * @param object
   *          A String or, an array of character bytes containing hexidecimal
   *          digits
   * @return A byte array containing binary data decoded from the supplied byte
   *         array (representing characters).
   * @throws DecoderException
   *           Thrown if an odd number of characters is supplied to this
   *           function or the object is not a String or char[]
   * @see #decodeHex(char[])
   */
  public Object decode(Object object) throws RuntimeException {
    try {
      char[] charArray = object instanceof String ? ((String) object).toCharArray()
          : (char[]) object;
      return decodeHex(charArray);
    } catch (ClassCastException e) {
      throw new RuntimeException(e.getMessage());
    }
  }
  /**
   * Converts an array of bytes into an array of bytes for the characters
   * representing the hexidecimal values of each byte in order. The returned
   * array will be double the length of the passed array, as it takes two
   * characters to represent any given byte.
   * 
   * @param array
   *          a byte[] to convert to Hex characters
   * @return A byte[] containing the bytes of the hexidecimal characters
   * @see #encodeHex(byte[])
   */
  public byte[] encode(byte[] array) {
    return new String(encodeHex(array)).getBytes();
  }
  /**
   * Converts a String or an array of bytes into an array of characters
   * representing the hexidecimal values of each byte in order. The returned
   * array will be double the length of the passed String or array, as it takes
   * two characters to represent any given byte.
   * 
   * @param object
   *          a String, or byte[] to convert to Hex characters
   * @return A char[] containing hexidecimal characters
   * @throws EncoderException
   *           Thrown if the given object is not a String or byte[]
   * @see #encodeHex(byte[])
   */
  public Object encode(Object object) throws Exception {
    try {
      byte[] byteArray = object instanceof String ? ((String) object).getBytes() : (byte[]) object;
      return encodeHex(byteArray);
    } catch (ClassCastException e) {
      throw new RuntimeException(e.getMessage());
    }
  }
}