The MessageDigest Class
The
MessageDigest class is an engine
class designed to provide the functionality of cryptographically secure message digests such
as SHA-1 or MD5. A cryptographically secure message digest takes arbitrary-sized input (a byte
array), and generates a fixed-size output, called a digest or hash. A digest has two
properties: - It should be computationally infeasible to find two messages that hashed to the same value.
- The digest should not reveal anything about the input that was used to generate it.
- Creating a
MessageDigestObject - The first step for computing a digest is to create a message digest instance. As with all engine classes, the way to get a
MessageDigestobject for a particular type of message digest algorithm is to call thegetInstancestatic factory method on theMessageDigestclass:static MessageDigest getInstance(String algorithm)Note: The algorithm name is not case-sensitive. For example, all the following calls are equivalent:MessageDigest.getInstance("SHA-1") MessageDigest.getInstance("sha-1") MessageDigest.getInstance("sHa-1")A caller might optionally specify the name of a provider or aProviderinstance, which guarantees that the implementation of the algorithm requested is from the specified provider:static MessageDigest getInstance(String algorithm, String provider) static MessageDigest getInstance(String algorithm, Provider provider)A call to
getInstancereturns an initialized message digest object. It therefore does not need further initialization. - Updating a Message Digest Object
- The next step for calculating the digest of some data is to supply the data to the initialized message digest object. This step is done by calling one of the
updatemethods:void update(byte input) void update(byte[] input) void update(byte[] input, int offset, int len) - Computing the Digest
- After the data has been supplied by calls to
updatemethods, the digest is computed using a call to one of thedigestmethods:byte[] digest() byte[] digest(byte[] input) int digest(byte[] buf, int offset, int len)The first two methods return the computed digest. The latter method stores the computed digest in the provided buffer
buf, starting atoffset.lenis the number of bytes inbufallotted for the digest. The method returns the number of bytes actually stored inbuf.A call to thedigestmethod that takes an input byte array argument is equivalent to making a call to the following method with the specified input, followed by a call to thedigestmethod without any arguments:void update(byte[] input)See the Examples section for more details.