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
MessageDigest
Object - The first step for computing a digest is to create a message digest instance. As with all engine classes, the way to get a
MessageDigest
object for a particular type of message digest algorithm is to call thegetInstance
static factory method on theMessageDigest
class: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 aProvider
instance, 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
getInstance
returns 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
update
methods: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
update
methods, the digest is computed using a call to one of thedigest
methods: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
.len
is the number of bytes inbuf
allotted for the digest. The method returns the number of bytes actually stored inbuf
.A call to thedigest
method 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 thedigest
method without any arguments:void update(byte[] input)
See the Examples section for more details.