1 package org.apache.maven.repository.digest;
4 * Copyright 2005-2006 The Apache Software Foundation.
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
10 * http://www.apache.org/licenses/LICENSE-2.0
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.
19 import java.io.IOException;
20 import java.io.InputStream;
21 import java.security.MessageDigest;
22 import java.security.NoSuchAlgorithmException;
25 * Gradually create a digest for a stream.
27 * @author <a href="mailto:brett@apache.org">Brett Porter</a>
29 public abstract class AbstractStreamingDigester
30 implements StreamingDigester
32 protected final MessageDigest md;
34 private static final char[] HEX_CHARS = "0123456789ABCDEF".toCharArray();
36 private static final int HI_MASK = 0xF0;
38 private static final int LO_MASK = 0x0F;
40 private static final int BUFFER_SIZE = 32768;
42 protected AbstractStreamingDigester( String algorithm )
43 throws NoSuchAlgorithmException
45 md = MessageDigest.getInstance( algorithm );
48 public String getAlgorithm()
50 return md.getAlgorithm();
54 throws DigesterException
56 return calc( this.md );
60 throws DigesterException
65 public void update( InputStream is )
66 throws DigesterException
71 protected static String calc( MessageDigest md )
73 byte[] digest = md.digest();
75 char[] hash = new char[digest.length * 2];
76 for ( int i = 0; i < digest.length; i++ )
78 hash[i * 2] = HEX_CHARS[( digest[i] & HI_MASK ) >> 4];
79 hash[i * 2 + 1] = HEX_CHARS[( digest[i] & LO_MASK )];
81 return new String( hash );
84 protected static void update( InputStream is, MessageDigest digest )
85 throws DigesterException
89 byte[] buffer = new byte[BUFFER_SIZE];
90 int size = is.read( buffer, 0, BUFFER_SIZE );
93 digest.update( buffer, 0, size );
94 size = is.read( buffer, 0, BUFFER_SIZE );
97 catch ( IOException e )
99 throw new DigesterException( "Unable to update " + digest.getAlgorithm() + " hash: " + e.getMessage(), e );