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
- 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
- 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 the
getInstancestatic factory method on the
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 a
Providerinstance, 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
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 the
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 at
lenis the number of bytes in
bufallotted for the digest. The method returns the number of bytes actually stored in
buf.A call to the
digestmethod 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 the
digestmethod without any arguments:
void update(byte input)
See the Examples section for more details.