0N/A/*
3909N/A * Copyright (c) 1996, 2011, Oracle and/or its affiliates. All rights reserved.
0N/A * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
0N/A *
0N/A * This code is free software; you can redistribute it and/or modify it
0N/A * under the terms of the GNU General Public License version 2 only, as
2362N/A * published by the Free Software Foundation. Oracle designates this
0N/A * particular file as subject to the "Classpath" exception as provided
2362N/A * by Oracle in the LICENSE file that accompanied this code.
0N/A *
0N/A * This code is distributed in the hope that it will be useful, but WITHOUT
0N/A * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
0N/A * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License
0N/A * version 2 for more details (a copy is included in the LICENSE file that
0N/A * accompanied this code).
0N/A *
0N/A * You should have received a copy of the GNU General Public License version
0N/A * 2 along with this work; if not, write to the Free Software Foundation,
0N/A * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
0N/A *
2362N/A * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
2362N/A * or visit www.oracle.com if you need additional information or have any
2362N/A * questions.
0N/A */
0N/A
0N/Apackage java.security;
0N/A
0N/Aimport java.util.*;
0N/Aimport java.lang.*;
0N/Aimport java.io.IOException;
0N/Aimport java.io.ByteArrayOutputStream;
0N/Aimport java.io.PrintStream;
0N/Aimport java.io.InputStream;
0N/Aimport java.io.ByteArrayInputStream;
0N/A
0N/Aimport java.nio.ByteBuffer;
0N/A
0N/A/**
0N/A * This MessageDigest class provides applications the functionality of a
3465N/A * message digest algorithm, such as SHA-1 or SHA-256.
0N/A * Message digests are secure one-way hash functions that take arbitrary-sized
0N/A * data and output a fixed-length hash value.
0N/A *
0N/A * <p>A MessageDigest object starts out initialized. The data is
0N/A * processed through it using the {@link #update(byte) update}
0N/A * methods. At any point {@link #reset() reset} can be called
0N/A * to reset the digest. Once all the data to be updated has been
0N/A * updated, one of the {@link #digest() digest} methods should
0N/A * be called to complete the hash computation.
0N/A *
0N/A * <p>The <code>digest</code> method can be called once for a given number
0N/A * of updates. After <code>digest</code> has been called, the MessageDigest
0N/A * object is reset to its initialized state.
0N/A *
0N/A * <p>Implementations are free to implement the Cloneable interface.
0N/A * Client applications can test cloneability by attempting cloning
0N/A * and catching the CloneNotSupportedException: <p>
0N/A *
0N/A* <pre>
0N/A* MessageDigest md = MessageDigest.getInstance("SHA");
0N/A*
0N/A* try {
0N/A* md.update(toChapter1);
0N/A* MessageDigest tc1 = md.clone();
0N/A* byte[] toChapter1Digest = tc1.digest();
0N/A* md.update(toChapter2);
0N/A* ...etc.
0N/A* } catch (CloneNotSupportedException cnse) {
0N/A* throw new DigestException("couldn't make digest of partial content");
0N/A* }
0N/A* </pre>
0N/A *
0N/A * <p>Note that if a given implementation is not cloneable, it is
0N/A * still possible to compute intermediate digests by instantiating
0N/A * several instances, if the number of digests is known in advance.
0N/A *
0N/A * <p>Note that this class is abstract and extends from
0N/A * <code>MessageDigestSpi</code> for historical reasons.
0N/A * Application developers should only take notice of the methods defined in
0N/A * this <code>MessageDigest</code> class; all the methods in
0N/A * the superclass are intended for cryptographic service providers who wish to
0N/A * supply their own implementations of message digest algorithms.
0N/A *
3465N/A * <p> Every implementation of the Java platform is required to support
3465N/A * the following standard <code>MessageDigest</code> algorithms:
3465N/A * <ul>
3465N/A * <li><tt>MD5</tt></li>
3465N/A * <li><tt>SHA-1</tt></li>
3465N/A * <li><tt>SHA-256</tt></li>
3465N/A * </ul>
3465N/A * These algorithms are described in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
3465N/A * MessageDigest section</a> of the
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation.
3465N/A * Consult the release documentation for your implementation to see if any
3465N/A * other algorithms are supported.
3465N/A *
0N/A * @author Benjamin Renaud
0N/A *
0N/A * @see DigestInputStream
0N/A * @see DigestOutputStream
0N/A */
0N/A
0N/Apublic abstract class MessageDigest extends MessageDigestSpi {
0N/A
0N/A private String algorithm;
0N/A
0N/A // The state of this digest
0N/A private static final int INITIAL = 0;
0N/A private static final int IN_PROGRESS = 1;
0N/A private int state = INITIAL;
0N/A
0N/A // The provider
0N/A private Provider provider;
0N/A
0N/A /**
0N/A * Creates a message digest with the specified algorithm name.
0N/A *
0N/A * @param algorithm the standard name of the digest algorithm.
3465N/A * See the MessageDigest section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A */
0N/A protected MessageDigest(String algorithm) {
0N/A this.algorithm = algorithm;
0N/A }
0N/A
0N/A /**
0N/A * Returns a MessageDigest object that implements the specified digest
0N/A * algorithm.
0N/A *
0N/A * <p> This method traverses the list of registered security Providers,
0N/A * starting with the most preferred Provider.
0N/A * A new MessageDigest object encapsulating the
0N/A * MessageDigestSpi implementation from the first
0N/A * Provider that supports the specified algorithm is returned.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
0N/A * @param algorithm the name of the algorithm requested.
3465N/A * See the MessageDigest section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @return a Message Digest object that implements the specified algorithm.
0N/A *
0N/A * @exception NoSuchAlgorithmException if no Provider supports a
0N/A * MessageDigestSpi implementation for the
0N/A * specified algorithm.
0N/A *
0N/A * @see Provider
0N/A */
0N/A public static MessageDigest getInstance(String algorithm)
0N/A throws NoSuchAlgorithmException {
0N/A try {
0N/A Object[] objs = Security.getImpl(algorithm, "MessageDigest",
0N/A (String)null);
0N/A if (objs[0] instanceof MessageDigest) {
0N/A MessageDigest md = (MessageDigest)objs[0];
0N/A md.provider = (Provider)objs[1];
0N/A return md;
0N/A } else {
0N/A MessageDigest delegate =
0N/A new Delegate((MessageDigestSpi)objs[0], algorithm);
0N/A delegate.provider = (Provider)objs[1];
0N/A return delegate;
0N/A }
0N/A } catch(NoSuchProviderException e) {
0N/A throw new NoSuchAlgorithmException(algorithm + " not found");
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a MessageDigest object that implements the specified digest
0N/A * algorithm.
0N/A *
0N/A * <p> A new MessageDigest object encapsulating the
0N/A * MessageDigestSpi implementation from the specified provider
0N/A * is returned. The specified provider must be registered
0N/A * in the security provider list.
0N/A *
0N/A * <p> Note that the list of registered providers may be retrieved via
0N/A * the {@link Security#getProviders() Security.getProviders()} method.
0N/A *
0N/A * @param algorithm the name of the algorithm requested.
3465N/A * See the MessageDigest section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @param provider the name of the provider.
0N/A *
0N/A * @return a MessageDigest object that implements the specified algorithm.
0N/A *
0N/A * @exception NoSuchAlgorithmException if a MessageDigestSpi
0N/A * implementation for the specified algorithm is not
0N/A * available from the specified provider.
0N/A *
0N/A * @exception NoSuchProviderException if the specified provider is not
0N/A * registered in the security provider list.
0N/A *
0N/A * @exception IllegalArgumentException if the provider name is null
0N/A * or empty.
0N/A *
0N/A * @see Provider
0N/A */
0N/A public static MessageDigest getInstance(String algorithm, String provider)
0N/A throws NoSuchAlgorithmException, NoSuchProviderException
0N/A {
0N/A if (provider == null || provider.length() == 0)
0N/A throw new IllegalArgumentException("missing provider");
0N/A Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
0N/A if (objs[0] instanceof MessageDigest) {
0N/A MessageDigest md = (MessageDigest)objs[0];
0N/A md.provider = (Provider)objs[1];
0N/A return md;
0N/A } else {
0N/A MessageDigest delegate =
0N/A new Delegate((MessageDigestSpi)objs[0], algorithm);
0N/A delegate.provider = (Provider)objs[1];
0N/A return delegate;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns a MessageDigest object that implements the specified digest
0N/A * algorithm.
0N/A *
0N/A * <p> A new MessageDigest object encapsulating the
0N/A * MessageDigestSpi implementation from the specified Provider
0N/A * object is returned. Note that the specified Provider object
0N/A * does not have to be registered in the provider list.
0N/A *
0N/A * @param algorithm the name of the algorithm requested.
3465N/A * See the MessageDigest section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @param provider the provider.
0N/A *
0N/A * @return a MessageDigest object that implements the specified algorithm.
0N/A *
0N/A * @exception NoSuchAlgorithmException if a MessageDigestSpi
0N/A * implementation for the specified algorithm is not available
0N/A * from the specified Provider object.
0N/A *
0N/A * @exception IllegalArgumentException if the specified provider is null.
0N/A *
0N/A * @see Provider
0N/A *
0N/A * @since 1.4
0N/A */
0N/A public static MessageDigest getInstance(String algorithm,
0N/A Provider provider)
0N/A throws NoSuchAlgorithmException
0N/A {
0N/A if (provider == null)
0N/A throw new IllegalArgumentException("missing provider");
0N/A Object[] objs = Security.getImpl(algorithm, "MessageDigest", provider);
0N/A if (objs[0] instanceof MessageDigest) {
0N/A MessageDigest md = (MessageDigest)objs[0];
0N/A md.provider = (Provider)objs[1];
0N/A return md;
0N/A } else {
0N/A MessageDigest delegate =
0N/A new Delegate((MessageDigestSpi)objs[0], algorithm);
0N/A delegate.provider = (Provider)objs[1];
0N/A return delegate;
0N/A }
0N/A }
0N/A
0N/A /**
0N/A * Returns the provider of this message digest object.
0N/A *
0N/A * @return the provider of this message digest object
0N/A */
0N/A public final Provider getProvider() {
0N/A return this.provider;
0N/A }
0N/A
0N/A /**
0N/A * Updates the digest using the specified byte.
0N/A *
0N/A * @param input the byte with which to update the digest.
0N/A */
0N/A public void update(byte input) {
0N/A engineUpdate(input);
0N/A state = IN_PROGRESS;
0N/A }
0N/A
0N/A /**
0N/A * Updates the digest using the specified array of bytes, starting
0N/A * at the specified offset.
0N/A *
0N/A * @param input the array of bytes.
0N/A *
0N/A * @param offset the offset to start from in the array of bytes.
0N/A *
0N/A * @param len the number of bytes to use, starting at
0N/A * <code>offset</code>.
0N/A */
0N/A public void update(byte[] input, int offset, int len) {
0N/A if (input == null) {
0N/A throw new IllegalArgumentException("No input buffer given");
0N/A }
0N/A if (input.length - offset < len) {
0N/A throw new IllegalArgumentException("Input buffer too short");
0N/A }
0N/A engineUpdate(input, offset, len);
0N/A state = IN_PROGRESS;
0N/A }
0N/A
0N/A /**
0N/A * Updates the digest using the specified array of bytes.
0N/A *
0N/A * @param input the array of bytes.
0N/A */
0N/A public void update(byte[] input) {
0N/A engineUpdate(input, 0, input.length);
0N/A state = IN_PROGRESS;
0N/A }
0N/A
0N/A /**
0N/A * Update the digest using the specified ByteBuffer. The digest is
0N/A * updated using the <code>input.remaining()</code> bytes starting
0N/A * at <code>input.position()</code>.
0N/A * Upon return, the buffer's position will be equal to its limit;
0N/A * its limit will not have changed.
0N/A *
0N/A * @param input the ByteBuffer
0N/A * @since 1.5
0N/A */
0N/A public final void update(ByteBuffer input) {
0N/A if (input == null) {
0N/A throw new NullPointerException();
0N/A }
0N/A engineUpdate(input);
0N/A state = IN_PROGRESS;
0N/A }
0N/A
0N/A /**
0N/A * Completes the hash computation by performing final operations
0N/A * such as padding. The digest is reset after this call is made.
0N/A *
0N/A * @return the array of bytes for the resulting hash value.
0N/A */
0N/A public byte[] digest() {
0N/A /* Resetting is the responsibility of implementors. */
0N/A byte[] result = engineDigest();
0N/A state = INITIAL;
0N/A return result;
0N/A }
0N/A
0N/A /**
0N/A * Completes the hash computation by performing final operations
0N/A * such as padding. The digest is reset after this call is made.
0N/A *
0N/A * @param buf output buffer for the computed digest
0N/A *
0N/A * @param offset offset into the output buffer to begin storing the digest
0N/A *
0N/A * @param len number of bytes within buf allotted for the digest
0N/A *
0N/A * @return the number of bytes placed into <code>buf</code>
0N/A *
0N/A * @exception DigestException if an error occurs.
0N/A */
0N/A public int digest(byte[] buf, int offset, int len) throws DigestException {
0N/A if (buf == null) {
0N/A throw new IllegalArgumentException("No output buffer given");
0N/A }
0N/A if (buf.length - offset < len) {
0N/A throw new IllegalArgumentException
0N/A ("Output buffer too small for specified offset and length");
0N/A }
0N/A int numBytes = engineDigest(buf, offset, len);
0N/A state = INITIAL;
0N/A return numBytes;
0N/A }
0N/A
0N/A /**
0N/A * Performs a final update on the digest using the specified array
0N/A * of bytes, then completes the digest computation. That is, this
0N/A * method first calls {@link #update(byte[]) update(input)},
0N/A * passing the <i>input</i> array to the <code>update</code> method,
0N/A * then calls {@link #digest() digest()}.
0N/A *
0N/A * @param input the input to be updated before the digest is
0N/A * completed.
0N/A *
0N/A * @return the array of bytes for the resulting hash value.
0N/A */
0N/A public byte[] digest(byte[] input) {
0N/A update(input);
0N/A return digest();
0N/A }
0N/A
0N/A /**
0N/A * Returns a string representation of this message digest object.
0N/A */
0N/A public String toString() {
0N/A ByteArrayOutputStream baos = new ByteArrayOutputStream();
0N/A PrintStream p = new PrintStream(baos);
0N/A p.print(algorithm+" Message Digest from "+provider.getName()+", ");
0N/A switch (state) {
0N/A case INITIAL:
0N/A p.print("<initialized>");
0N/A break;
0N/A case IN_PROGRESS:
0N/A p.print("<in progress>");
0N/A break;
0N/A }
0N/A p.println();
0N/A return (baos.toString());
0N/A }
0N/A
0N/A /**
0N/A * Compares two digests for equality. Does a simple byte compare.
0N/A *
0N/A * @param digesta one of the digests to compare.
0N/A *
0N/A * @param digestb the other digest to compare.
0N/A *
0N/A * @return true if the digests are equal, false otherwise.
0N/A */
1842N/A public static boolean isEqual(byte[] digesta, byte[] digestb) {
1842N/A if (digesta.length != digestb.length) {
0N/A return false;
1842N/A }
0N/A
1842N/A int result = 0;
1842N/A // time-constant comparison
0N/A for (int i = 0; i < digesta.length; i++) {
1842N/A result |= digesta[i] ^ digestb[i];
0N/A }
1842N/A return result == 0;
0N/A }
0N/A
0N/A /**
0N/A * Resets the digest for further use.
0N/A */
0N/A public void reset() {
0N/A engineReset();
0N/A state = INITIAL;
0N/A }
0N/A
0N/A /**
0N/A * Returns a string that identifies the algorithm, independent of
0N/A * implementation details. The name should be a standard
0N/A * Java Security name (such as "SHA", "MD5", and so on).
3465N/A * See the MessageDigest section in the <a href=
3465N/A * "{@docRoot}/../technotes/guides/security/StandardNames.html#MessageDigest">
3465N/A * Java Cryptography Architecture Standard Algorithm Name Documentation</a>
0N/A * for information about standard algorithm names.
0N/A *
0N/A * @return the name of the algorithm
0N/A */
0N/A public final String getAlgorithm() {
0N/A return this.algorithm;
0N/A }
0N/A
0N/A /**
0N/A * Returns the length of the digest in bytes, or 0 if this operation is
0N/A * not supported by the provider and the implementation is not cloneable.
0N/A *
0N/A * @return the digest length in bytes, or 0 if this operation is not
0N/A * supported by the provider and the implementation is not cloneable.
0N/A *
0N/A * @since 1.2
0N/A */
0N/A public final int getDigestLength() {
0N/A int digestLen = engineGetDigestLength();
0N/A if (digestLen == 0) {
0N/A try {
0N/A MessageDigest md = (MessageDigest)clone();
0N/A byte[] digest = md.digest();
0N/A return digest.length;
0N/A } catch (CloneNotSupportedException e) {
0N/A return digestLen;
0N/A }
0N/A }
0N/A return digestLen;
0N/A }
0N/A
0N/A /**
0N/A * Returns a clone if the implementation is cloneable.
0N/A *
0N/A * @return a clone if the implementation is cloneable.
0N/A *
0N/A * @exception CloneNotSupportedException if this is called on an
0N/A * implementation that does not support <code>Cloneable</code>.
0N/A */
0N/A public Object clone() throws CloneNotSupportedException {
0N/A if (this instanceof Cloneable) {
0N/A return super.clone();
0N/A } else {
0N/A throw new CloneNotSupportedException();
0N/A }
0N/A }
0N/A
0N/A
0N/A
0N/A
0N/A /*
0N/A * The following class allows providers to extend from MessageDigestSpi
0N/A * rather than from MessageDigest. It represents a MessageDigest with an
0N/A * encapsulated, provider-supplied SPI object (of type MessageDigestSpi).
0N/A * If the provider implementation is an instance of MessageDigestSpi,
0N/A * the getInstance() methods above return an instance of this class, with
0N/A * the SPI object encapsulated.
0N/A *
0N/A * Note: All SPI methods from the original MessageDigest class have been
0N/A * moved up the hierarchy into a new class (MessageDigestSpi), which has
0N/A * been interposed in the hierarchy between the API (MessageDigest)
0N/A * and its original parent (Object).
0N/A */
0N/A
0N/A static class Delegate extends MessageDigest {
0N/A
0N/A // The provider implementation (delegate)
0N/A private MessageDigestSpi digestSpi;
0N/A
0N/A // constructor
0N/A public Delegate(MessageDigestSpi digestSpi, String algorithm) {
0N/A super(algorithm);
0N/A this.digestSpi = digestSpi;
0N/A }
0N/A
0N/A /**
0N/A * Returns a clone if the delegate is cloneable.
0N/A *
0N/A * @return a clone if the delegate is cloneable.
0N/A *
0N/A * @exception CloneNotSupportedException if this is called on a
0N/A * delegate that does not support <code>Cloneable</code>.
0N/A */
0N/A public Object clone() throws CloneNotSupportedException {
0N/A if (digestSpi instanceof Cloneable) {
0N/A MessageDigestSpi digestSpiClone =
0N/A (MessageDigestSpi)digestSpi.clone();
0N/A // Because 'algorithm', 'provider', and 'state' are private
0N/A // members of our supertype, we must perform a cast to
0N/A // access them.
0N/A MessageDigest that =
0N/A new Delegate(digestSpiClone,
0N/A ((MessageDigest)this).algorithm);
0N/A that.provider = ((MessageDigest)this).provider;
0N/A that.state = ((MessageDigest)this).state;
0N/A return that;
0N/A } else {
0N/A throw new CloneNotSupportedException();
0N/A }
0N/A }
0N/A
0N/A protected int engineGetDigestLength() {
0N/A return digestSpi.engineGetDigestLength();
0N/A }
0N/A
0N/A protected void engineUpdate(byte input) {
0N/A digestSpi.engineUpdate(input);
0N/A }
0N/A
0N/A protected void engineUpdate(byte[] input, int offset, int len) {
0N/A digestSpi.engineUpdate(input, offset, len);
0N/A }
0N/A
0N/A protected void engineUpdate(ByteBuffer input) {
0N/A digestSpi.engineUpdate(input);
0N/A }
0N/A
0N/A protected byte[] engineDigest() {
0N/A return digestSpi.engineDigest();
0N/A }
0N/A
0N/A protected int engineDigest(byte[] buf, int offset, int len)
0N/A throws DigestException {
0N/A return digestSpi.engineDigest(buf, offset, len);
0N/A }
0N/A
0N/A protected void engineReset() {
0N/A digestSpi.engineReset();
0N/A }
0N/A }
0N/A}