FileDocCategorySizeDatePackage
MessageDigest.javaAPI DocJava SE 5 API17201Fri Aug 26 14:57:14 BST 2005java.security

MessageDigest

public abstract class MessageDigest extends MessageDigestSpi
This MessageDigest class provides applications the functionality of a message digest algorithm, such as MD5 or SHA. Message digests are secure one-way hash functions that take arbitrary-sized data and output a fixed-length hash value.

A MessageDigest object starts out initialized. The data is processed through it using the {@link #update(byte) update} methods. At any point {@link #reset() reset} can be called to reset the digest. Once all the data to be updated has been updated, one of the {@link #digest() digest} methods should be called to complete the hash computation.

The digest method can be called once for a given number of updates. After digest has been called, the MessageDigest object is reset to its initialized state.

Implementations are free to implement the Cloneable interface. Client applications can test cloneability by attempting cloning and catching the CloneNotSupportedException:

MessageDigest md = MessageDigest.getInstance("SHA");

try {
md.update(toChapter1);
MessageDigest tc1 = md.clone();
byte[] toChapter1Digest = tc1.digest();
md.update(toChapter2);
...etc.
} catch (CloneNotSupportedException cnse) {
throw new DigestException("couldn't make digest of partial content");
}

Note that if a given implementation is not cloneable, it is still possible to compute intermediate digests by instantiating several instances, if the number of digests is known in advance.

Note that this class is abstract and extends from MessageDigestSpi for historical reasons. Application developers should only take notice of the methods defined in this MessageDigest class; all the methods in the superclass are intended for cryptographic service providers who wish to supply their own implementations of message digest algorithms.

author
Benjamin Renaud
version
1.77, 12/19/03
see
DigestInputStream
see
DigestOutputStream

Fields Summary
private String
algorithm
private static final int
INITIAL
private static final int
IN_PROGRESS
private int
state
private Provider
provider
Constructors Summary
protected MessageDigest(String algorithm)
Creates a message digest with the specified algorithm name.

param
algorithm the standard name of the digest algorithm. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.


                                                    
       
	this.algorithm = algorithm;
    
Methods Summary
public java.lang.Objectclone()
Returns a clone if the implementation is cloneable.

return
a clone if the implementation is cloneable.
exception
CloneNotSupportedException if this is called on an implementation that does not support Cloneable.

	if (this instanceof Cloneable) {
	    return super.clone();
	} else {
	    throw new CloneNotSupportedException();
	}
    
public byte[]digest()
Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made.

return
the array of bytes for the resulting hash value.

	/* Resetting is the responsibility of implementors. */
	byte[] result = engineDigest();
	state = INITIAL;
	return result;
    
public intdigest(byte[] buf, int offset, int len)
Completes the hash computation by performing final operations such as padding. The digest is reset after this call is made.

param
buf output buffer for the computed digest
param
offset offset into the output buffer to begin storing the digest
param
len number of bytes within buf allotted for the digest
return
the number of bytes placed into buf
exception
DigestException if an error occurs.

	if (buf == null) {
	    throw new IllegalArgumentException("No output buffer given");
	}
	if (buf.length - offset < len) {
	    throw new IllegalArgumentException
		("Output buffer too small for specified offset and length");
	}
	int numBytes = engineDigest(buf, offset, len);
	state = INITIAL;
	return numBytes;
    
public byte[]digest(byte[] input)
Performs a final update on the digest using the specified array of bytes, then completes the digest computation. That is, this method first calls {@link #update(byte[]) update(input)}, passing the input array to the update method, then calls {@link #digest() digest()}.

param
input the input to be updated before the digest is completed.
return
the array of bytes for the resulting hash value.

	update(input);
	return digest();
    
public final java.lang.StringgetAlgorithm()
Returns a string that identifies the algorithm, independent of implementation details. The name should be a standard Java Security name (such as "SHA", "MD5", and so on). See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.

return
the name of the algorithm

	return this.algorithm;
    
public final intgetDigestLength()
Returns the length of the digest in bytes, or 0 if this operation is not supported by the provider and the implementation is not cloneable.

return
the digest length in bytes, or 0 if this operation is not supported by the provider and the implementation is not cloneable.
since
1.2

	int digestLen = engineGetDigestLength();
	if (digestLen == 0) {
	    try {
		MessageDigest md = (MessageDigest)clone();
		byte[] digest = md.digest();
		return digest.length;
	    } catch (CloneNotSupportedException e) {
		return digestLen;
	    }
	}
	return digestLen;
    
public static java.security.MessageDigestgetInstance(java.lang.String algorithm)
Generates a MessageDigest object that implements the specified digest algorithm. If the default provider package provides an implementation of the requested digest algorithm, an instance of MessageDigest containing that implementation is returned. If the algorithm is not available in the default package, other packages are searched.

param
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
return
a Message Digest object implementing the specified algorithm.
exception
NoSuchAlgorithmException if the algorithm is not available in the caller's environment.

 
	try {
	    Object[] objs = Security.getImpl(algorithm, "MessageDigest",
					     (String)null);
	    if (objs[0] instanceof MessageDigest) {
		MessageDigest md = (MessageDigest)objs[0];
		md.provider = (Provider)objs[1];
		return md;
	    } else {
		MessageDigest delegate =
		    new Delegate((MessageDigestSpi)objs[0], algorithm);
		delegate.provider = (Provider)objs[1];
		return delegate;
	    }
	} catch(NoSuchProviderException e) {
	    throw new NoSuchAlgorithmException(algorithm + " not found");
	}
    
public static java.security.MessageDigestgetInstance(java.lang.String algorithm, java.lang.String provider)
Generates a MessageDigest object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider.

param
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
param
provider the name of the provider.
return
a Message Digest object implementing the specified algorithm.
exception
NoSuchAlgorithmException if the algorithm is not available in the package supplied by the requested provider.
exception
NoSuchProviderException if the provider is not available in the environment.
exception
IllegalArgumentException if the provider name is null or empty.
see
Provider

	if (provider == null || provider.length() == 0)
	    throw new IllegalArgumentException("missing provider");
	Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
	if (objs[0] instanceof MessageDigest) {
	    MessageDigest md = (MessageDigest)objs[0];
	    md.provider = (Provider)objs[1];
	    return md;
	} else {
	    MessageDigest delegate =
		new Delegate((MessageDigestSpi)objs[0], algorithm);
	    delegate.provider = (Provider)objs[1];
	    return delegate;
	}
    
public static java.security.MessageDigestgetInstance(java.lang.String algorithm, java.security.Provider provider)
Generates a MessageDigest object implementing the specified algorithm, as supplied from the specified provider, if such an algorithm is available from the provider. Note: the provider doesn't have to be registered.

param
algorithm the name of the algorithm requested. See Appendix A in the Java Cryptography Architecture API Specification & Reference for information about standard algorithm names.
param
provider the provider.
return
a Message Digest object implementing the specified algorithm.
exception
NoSuchAlgorithmException if the algorithm is not available in the package supplied by the requested provider.
exception
IllegalArgumentException if the provider is null.
see
Provider
since
1.4

	if (provider == null)
	    throw new IllegalArgumentException("missing provider");
	Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
	if (objs[0] instanceof MessageDigest) {
	    MessageDigest md = (MessageDigest)objs[0];
	    md.provider = (Provider)objs[1];
	    return md;
	} else {
	    MessageDigest delegate =
		new Delegate((MessageDigestSpi)objs[0], algorithm);
	    delegate.provider = (Provider)objs[1];
	    return delegate;
	}
    
public final java.security.ProvidergetProvider()
Returns the provider of this message digest object.

return
the provider of this message digest object

	return this.provider;
    
public static booleanisEqual(byte[] digesta, byte[] digestb)
Compares two digests for equality. Does a simple byte compare.

param
digesta one of the digests to compare.
param
digestb the other digest to compare.
return
true if the digests are equal, false otherwise.

	if (digesta.length != digestb.length)
	    return false;

	for (int i = 0; i < digesta.length; i++) {
	    if (digesta[i] != digestb[i]) {
		return false;
	    }
	}
	return true;
    
public voidreset()
Resets the digest for further use.

	engineReset();
	state = INITIAL;
    
public java.lang.StringtoString()
Returns a string representation of this message digest object.

	ByteArrayOutputStream baos = new ByteArrayOutputStream();
	PrintStream p = new PrintStream(baos);
	p.print(algorithm+" Message Digest from "+provider.getName()+", ");
	switch (state) {
	case INITIAL:
	    p.print("<initialized>");
	    break;
	case IN_PROGRESS:
	    p.print("<in progress>");
	    break;
	}
	p.println();
	return (baos.toString());
    
public voidupdate(byte input)
Updates the digest using the specified byte.

param
input the byte with which to update the digest.

	engineUpdate(input);
	state = IN_PROGRESS;
    
public voidupdate(byte[] input, int offset, int len)
Updates the digest using the specified array of bytes, starting at the specified offset.

param
input the array of bytes.
param
offset the offset to start from in the array of bytes.
param
len the number of bytes to use, starting at offset.

	if (input == null) {
	    throw new IllegalArgumentException("No input buffer given");
	}
	if (input.length - offset < len) {
	    throw new IllegalArgumentException("Input buffer too short");
	}
	engineUpdate(input, offset, len);
	state = IN_PROGRESS;
    
public voidupdate(byte[] input)
Updates the digest using the specified array of bytes.

param
input the array of bytes.

	engineUpdate(input, 0, input.length);
	state = IN_PROGRESS;
    
public final voidupdate(java.nio.ByteBuffer input)
Update the digest using the specified ByteBuffer. The digest is updated using the input.remaining() bytes starting at input.position(). Upon return, the buffer's position will be equal to its limit; its limit will not have changed.

param
input the ByteBuffer
since
1.5

	if (input == null) {
	    throw new NullPointerException();
	}
	engineUpdate(input);
	state = IN_PROGRESS;