View Javadoc
1   package org.codehaus.plexus.digest;
2   
3   /*
4    * Copyright 2001-2006 The Codehaus.
5    *
6    * Licensed under the Apache License, Version 2.0 (the "License");
7    * you may not use this file except in compliance with the License.
8    * You may obtain a copy of the License at
9    *
10   *      http://www.apache.org/licenses/LICENSE-2.0
11   *
12   * Unless required by applicable law or agreed to in writing, software
13   * distributed under the License is distributed on an "AS IS" BASIS,
14   * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15   * See the License for the specific language governing permissions and
16   * limitations under the License.
17   */
18  
19  import java.io.IOException;
20  import java.io.InputStream;
21  import java.security.MessageDigest;
22  import java.security.NoSuchAlgorithmException;
23  
24  /**
25   * Gradually create a digest for a stream.
26   *
27   * @author <a href="mailto:brett@apache.org">Brett Porter</a>
28   */
29  public abstract class AbstractStreamingDigester
30      implements StreamingDigester
31  {
32      protected final MessageDigest md;
33  
34      private static final int BUFFER_SIZE = 32768;
35  
36      protected AbstractStreamingDigester( String algorithm )
37      {
38          try
39          {
40              md = MessageDigest.getInstance( algorithm );
41          }
42          catch ( NoSuchAlgorithmException e )
43          {
44              throw new IllegalStateException( "Unable to initialize digest algorithm " + algorithm + " : "
45                  + e.getMessage() );
46          }
47      }
48  
49      public String getAlgorithm()
50      {
51          return md.getAlgorithm();
52      }
53  
54      public String calc()
55          throws DigesterException
56      {
57          return calc( this.md );
58      }
59  
60      public void reset()
61          throws DigesterException
62      {
63          md.reset();
64      }
65  
66      public void update( InputStream is )
67          throws DigesterException
68      {
69          update( is, md );
70      }
71  
72      protected static String calc( MessageDigest md )
73      {
74          return Hex.encode( md.digest() );
75      }
76  
77      protected static void update( InputStream is, MessageDigest digest )
78          throws DigesterException
79      {
80          try
81          {
82              byte[] buffer = new byte[BUFFER_SIZE];
83              int size = is.read( buffer, 0, BUFFER_SIZE );
84              while ( size >= 0 )
85              {
86                  digest.update( buffer, 0, size );
87                  size = is.read( buffer, 0, BUFFER_SIZE );
88              }
89          }
90          catch ( IOException e )
91          {
92              throw new DigesterException( "Unable to update " + digest.getAlgorithm() + " hash: " + e.getMessage(), e );
93          }
94      }
95  }