jdk/src/share/classes/sun/jkernel/StandaloneMessageDigest.java
changeset 8197 e45f21c2a40b
parent 7867 f83cd8bd35c6
child 8198 aca2f99e4b52
equal deleted inserted replaced
7867:f83cd8bd35c6 8197:e45f21c2a40b
     1 /*
       
     2  * Copyright (c) 2008, 2009, Oracle and/or its affiliates. All rights reserved.
       
     3  * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
       
     4  *
       
     5  * This code is free software; you can redistribute it and/or modify it
       
     6  * under the terms of the GNU General Public License version 2 only, as
       
     7  * published by the Free Software Foundation.  Oracle designates this
       
     8  * particular file as subject to the "Classpath" exception as provided
       
     9  * by Oracle in the LICENSE file that accompanied this code.
       
    10  *
       
    11  * This code is distributed in the hope that it will be useful, but WITHOUT
       
    12  * ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
       
    13  * FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
       
    14  * version 2 for more details (a copy is included in the LICENSE file that
       
    15  * accompanied this code).
       
    16  *
       
    17  * You should have received a copy of the GNU General Public License version
       
    18  * 2 along with this work; if not, write to the Free Software Foundation,
       
    19  * Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA.
       
    20  *
       
    21  * Please contact Oracle, 500 Oracle Parkway, Redwood Shores, CA 94065 USA
       
    22  * or visit www.oracle.com if you need additional information or have any
       
    23  * questions.
       
    24  */
       
    25 
       
    26 /*
       
    27  * This is a combination and adaptation of subsets of
       
    28  * <code>java.security.MessageDigest</code> and
       
    29  * <code>sun.security.provider.DigestBase</code> to provide a class offering
       
    30  * most of the same public methods of <code>MessageDigest</code> while not
       
    31  * depending on the Java Security Framework.
       
    32  * <p>
       
    33  * One algorithm is currently supported: "SHA-1".
       
    34  * <p>
       
    35  * NOTE If <code>java.security.MessageDigest</code>,
       
    36  * <code>sun.security.provider.DigestBase</code> or
       
    37  * <code>sun.security.provider.SHA</code> are modified, review of those
       
    38  * modifications should be done to determine any possible implications for this
       
    39  * class and <code>StandaloneSHA</code>.
       
    40  */
       
    41 
       
    42 package sun.jkernel;
       
    43 
       
    44 import java.security.DigestException;
       
    45 import java.security.ProviderException;
       
    46 import java.security.NoSuchAlgorithmException;
       
    47 
       
    48 /**
       
    49  * (Adapted from the <code>sun.security.provider.DigestBase</code> doc).
       
    50  * This is a simple subset of the Common base message digest implementation
       
    51  * for the Sun provider.
       
    52  * It implements most of the JCA methods as suitable for a Java message
       
    53  * digest
       
    54  * implementation of an algorithm based on a compression function (as all
       
    55  * commonly used algorithms are). The individual digest subclasses only need to
       
    56  * implement the following methods:
       
    57  *
       
    58  *  . abstract void implCompress(byte[] b, int ofs);
       
    59  *  . abstract void implDigest(byte[] out, int ofs);
       
    60  *  . abstract void implReset();
       
    61  * <p>
       
    62  * No support for a clone() method is provided.
       
    63  * <p>
       
    64  * See the inline documentation for details.
       
    65  *
       
    66  * @since   1.5
       
    67  * @version 1.3, 08/08/07
       
    68  * @author  Andreas Sterbenz (MessageDigest)
       
    69  * @author  Pete Soper (this derived class)
       
    70  */
       
    71 public abstract class StandaloneMessageDigest {
       
    72 
       
    73      public static final boolean debug = false;
       
    74 
       
    75     /*
       
    76      * (Copied/adapted from <code>java.security.MessageDigest</code>
       
    77      *
       
    78      * This is a subset/simplification <code>java.security.MessageDigest</code>
       
    79      * that supports a fixed set of hashcode mechanisms (currently just
       
    80      * SHA-1) while preserving the following MessageDigest methods:
       
    81      *
       
    82      * public MessageDigest getInstance(String algorithm)
       
    83      * public final int getDigestLength()
       
    84      * public void reset()
       
    85      * public byte[] digest()
       
    86      * public void update(byte[] input, int offset, int len)
       
    87      * public final String getAlgorithm()
       
    88      * <p>
       
    89      * NOTE that the clone() method is not provided.
       
    90      */
       
    91 
       
    92     /**
       
    93      * Prevent direct instantiation except via the factory method.
       
    94      */
       
    95 
       
    96     private StandaloneMessageDigest() {
       
    97         // Keep javac happy.
       
    98         digestLength = 0;
       
    99         blockSize = 0;
       
   100         algorithm = null;
       
   101         buffer = null;
       
   102     }
       
   103 
       
   104     private String algorithm;
       
   105 
       
   106     // The state of this digest
       
   107     private static final int INITIAL = 0;
       
   108     private static final int IN_PROGRESS = 1;
       
   109     private int state = INITIAL;
       
   110 
       
   111     /**
       
   112      * Returns a StandaloneMessageDigest object that implements the specified
       
   113      * digest algorithm.
       
   114      *
       
   115      * <p> This method returns a new StandaloneMessageDigest for a single
       
   116      * algorithm provider.
       
   117      *
       
   118      * @param algorithm the name of the algorithm requested.
       
   119      *
       
   120      * @return a standalone Message Digest object that implements the specified algorithm.
       
   121      *
       
   122      * @exception NoSuchAlgorithmException if algorithm not supported
       
   123      *
       
   124      */
       
   125     public static StandaloneMessageDigest getInstance(String algorithm)
       
   126         throws NoSuchAlgorithmException {
       
   127         if (! algorithm.equals("SHA-1")) {
       
   128             throw new NoSuchAlgorithmException(algorithm + " not found");
       
   129         } else {
       
   130             return new StandaloneSHA();
       
   131         }
       
   132     }
       
   133 
       
   134     /**
       
   135      * Updates the digest using the specified array of bytes, starting
       
   136      * at the specified offset.
       
   137      *
       
   138      * @param input the array of bytes.
       
   139      *
       
   140      * @param offset the offset to start from in the array of bytes.
       
   141      *
       
   142      * @param len the number of bytes to use, starting at
       
   143      * <code>offset</code>.
       
   144      */
       
   145     public void update(byte[] input, int offset, int len) {
       
   146         if (debug) {
       
   147             System.out.println("StandaloneMessageDigest.update");
       
   148             (new Exception()).printStackTrace();
       
   149         }
       
   150         if (input == null) {
       
   151             throw new IllegalArgumentException("No input buffer given");
       
   152         }
       
   153         if (input.length - offset < len) {
       
   154             throw new IllegalArgumentException("Input buffer too short");
       
   155         }
       
   156         // No need to check for negative offset: engineUpdate does this
       
   157 
       
   158         engineUpdate(input, offset, len);
       
   159         state = IN_PROGRESS;
       
   160     }
       
   161 
       
   162     /**
       
   163      * Completes the hash computation by performing final operations
       
   164      * such as padding. The digest is reset after this call is made.
       
   165      *
       
   166      * @return the array of bytes for the resulting hash value.
       
   167      */
       
   168     public byte[] digest() {
       
   169         if (debug) {
       
   170             System.out.println("StandaloneMessageDigest.digest");
       
   171         }
       
   172         /* Resetting is the responsibility of implementors. */
       
   173         byte[] result = engineDigest();
       
   174         state = INITIAL;
       
   175         return result;
       
   176     }
       
   177 
       
   178     /**
       
   179      * Compares two digests for equality. Does a simple byte compare.
       
   180      *
       
   181      * @param digesta one of the digests to compare.
       
   182      *
       
   183      * @param digestb the other digest to compare.
       
   184      *
       
   185      * @return true if the digests are equal, false otherwise.
       
   186      */
       
   187     public static boolean isEqual(byte digesta[], byte digestb[]) {
       
   188         if (digesta.length != digestb.length)
       
   189             return false;
       
   190 
       
   191         for (int i = 0; i < digesta.length; i++) {
       
   192             if (digesta[i] != digestb[i]) {
       
   193                 return false;
       
   194             }
       
   195         }
       
   196         return true;
       
   197     }
       
   198 
       
   199     /**
       
   200      * Resets the digest for further use.
       
   201      */
       
   202     public void reset() {
       
   203         if (debug) {
       
   204             System.out.println("StandaloneMessageDigest.reset");
       
   205         }
       
   206         engineReset();
       
   207         state = INITIAL;
       
   208     }
       
   209 
       
   210     /**
       
   211      * Returns a string that identifies the algorithm, independent of
       
   212      * implementation details. The name should be a standard
       
   213      * Java Security name (such as "SHA", "MD5", and so on).
       
   214      * See Appendix A in the <a href=
       
   215      * "../../../technotes/guides/security/crypto/CryptoSpec.html#AppA">
       
   216      * Java Cryptography Architecture API Specification &amp; Reference </a>
       
   217      * for information about standard algorithm names.
       
   218      *
       
   219      * @return the name of the algorithm
       
   220      */
       
   221     public final String getAlgorithm() {
       
   222         return this.algorithm;
       
   223     }
       
   224 
       
   225     /**
       
   226      * Returns the length of the digest in bytes.
       
   227      *
       
   228      * @return the digest length in bytes.
       
   229      *
       
   230      * @since 1.2
       
   231      */
       
   232     public final int getDigestLength() {
       
   233         return engineGetDigestLength();
       
   234     }
       
   235 
       
   236     //* End of copied/adapted <code>java.security.MessageDigest</code>
       
   237 
       
   238     // Start of copied/adapted <code>sun.security.provider.DigestBase</code>
       
   239 
       
   240     // one element byte array, temporary storage for update(byte)
       
   241     private byte[] oneByte;
       
   242 
       
   243     // length of the message digest in bytes
       
   244     private final int digestLength;
       
   245 
       
   246     // size of the input to the compression function in bytes
       
   247     private final int blockSize;
       
   248     // buffer to store partial blocks, blockSize bytes large
       
   249     // Subclasses should not access this array directly except possibly in their
       
   250     // implDigest() method. See MD5.java as an example.
       
   251     final byte[] buffer;
       
   252     // offset into buffer
       
   253     private int bufOfs;
       
   254 
       
   255     // number of bytes processed so far. subclasses should not modify
       
   256     // this value.
       
   257     // also used as a flag to indicate reset status
       
   258     // -1: need to call engineReset() before next call to update()
       
   259     //  0: is already reset
       
   260     long bytesProcessed;
       
   261 
       
   262     /**
       
   263      * Main constructor.
       
   264      */
       
   265     StandaloneMessageDigest(String algorithm, int digestLength, int blockSize) {
       
   266         // super();
       
   267         this.algorithm = algorithm;
       
   268         this.digestLength = digestLength;
       
   269         this.blockSize = blockSize;
       
   270         buffer = new byte[blockSize];
       
   271     }
       
   272 
       
   273     // return digest length. See JCA doc.
       
   274     protected final int engineGetDigestLength() {
       
   275         return digestLength;
       
   276     }
       
   277 
       
   278     // single byte update. See JCA doc.
       
   279     protected final void engineUpdate(byte b) {
       
   280         if (oneByte == null) {
       
   281             oneByte = new byte[1];
       
   282         }
       
   283         oneByte[0] = b;
       
   284         engineUpdate(oneByte, 0, 1);
       
   285     }
       
   286 
       
   287     // array update. See JCA doc.
       
   288     protected final void engineUpdate(byte[] b, int ofs, int len) {
       
   289         if (len == 0) {
       
   290             return;
       
   291         }
       
   292         if ((ofs < 0) || (len < 0) || (ofs > b.length - len)) {
       
   293             throw new ArrayIndexOutOfBoundsException();
       
   294         }
       
   295         if (bytesProcessed < 0) {
       
   296             engineReset();
       
   297         }
       
   298         bytesProcessed += len;
       
   299         // if buffer is not empty, we need to fill it before proceeding
       
   300         if (bufOfs != 0) {
       
   301             int n = Math.min(len, blockSize - bufOfs);
       
   302             System.arraycopy(b, ofs, buffer, bufOfs, n);
       
   303             bufOfs += n;
       
   304             ofs += n;
       
   305             len -= n;
       
   306             if (bufOfs >= blockSize) {
       
   307                 // compress completed block now
       
   308                 implCompress(buffer, 0);
       
   309                 bufOfs = 0;
       
   310             }
       
   311         }
       
   312         // compress complete blocks
       
   313         while (len >= blockSize) {
       
   314             implCompress(b, ofs);
       
   315             len -= blockSize;
       
   316             ofs += blockSize;
       
   317         }
       
   318         // copy remainder to buffer
       
   319         if (len > 0) {
       
   320             System.arraycopy(b, ofs, buffer, 0, len);
       
   321             bufOfs = len;
       
   322         }
       
   323     }
       
   324 
       
   325     // reset this object. See JCA doc.
       
   326     protected final void engineReset() {
       
   327         if (bytesProcessed == 0) {
       
   328             // already reset, ignore
       
   329             return;
       
   330         }
       
   331         implReset();
       
   332         bufOfs = 0;
       
   333         bytesProcessed = 0;
       
   334     }
       
   335 
       
   336     // return the digest. See JCA doc.
       
   337     protected final byte[] engineDigest() throws ProviderException {
       
   338         byte[] b = new byte[digestLength];
       
   339         try {
       
   340             engineDigest(b, 0, b.length);
       
   341         } catch (DigestException e) {
       
   342             throw (ProviderException)
       
   343                 new ProviderException("Internal error").initCause(e);
       
   344         }
       
   345         return b;
       
   346     }
       
   347 
       
   348     // return the digest in the specified array. See JCA doc.
       
   349     protected final int engineDigest(byte[] out, int ofs, int len)
       
   350             throws DigestException {
       
   351         if (len < digestLength) {
       
   352             throw new DigestException("Length must be at least "
       
   353                 + digestLength + " for " + algorithm + "digests");
       
   354         }
       
   355         if ((ofs < 0) || (len < 0) || (ofs > out.length - len)) {
       
   356             throw new DigestException("Buffer too short to store digest");
       
   357         }
       
   358         if (bytesProcessed < 0) {
       
   359             engineReset();
       
   360         }
       
   361         implDigest(out, ofs);
       
   362         bytesProcessed = -1;
       
   363         return digestLength;
       
   364     }
       
   365 
       
   366     /**
       
   367      * Core compression function. Processes blockSize bytes at a time
       
   368      * and updates the state of this object.
       
   369      */
       
   370     abstract void implCompress(byte[] b, int ofs);
       
   371 
       
   372     /**
       
   373      * Return the digest. Subclasses do not need to reset() themselves,
       
   374      * StandaloneMessageDigest calls implReset() when necessary.
       
   375      */
       
   376     abstract void implDigest(byte[] out, int ofs);
       
   377 
       
   378     /**
       
   379      * Reset subclass specific state to their initial values. StandaloneMessageDigest
       
   380      * calls this method when necessary.
       
   381      */
       
   382     abstract void implReset();
       
   383 
       
   384     // padding used for the MD5, and SHA-* message digests
       
   385     static final byte[] padding;
       
   386 
       
   387     static {
       
   388         // we need 128 byte padding for SHA-384/512
       
   389         // and an additional 8 bytes for the high 8 bytes of the 16
       
   390         // byte bit counter in SHA-384/512
       
   391         padding = new byte[136];
       
   392         padding[0] = (byte)0x80;
       
   393     }
       
   394 
       
   395 }