1 package org.apache.archiva.checksum;
4 * Licensed to the Apache Software Foundation (ASF) under one
5 * or more contributor license agreements. See the NOTICE file
6 * distributed with this work for additional information
7 * regarding copyright ownership. The ASF licenses this file
8 * to you under the Apache License, Version 2.0 (the
9 * "License"); you may not use this file except in compliance
10 * with the License. You may obtain a copy of the License at
12 * http://www.apache.org/licenses/LICENSE-2.0
14 * Unless required by applicable law or agreed to in writing,
15 * software distributed under the License is distributed on an
16 * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
17 * KIND, either express or implied. See the License for the
18 * specific language governing permissions and limitations
22 import org.apache.commons.io.IOUtils;
23 import org.apache.commons.io.output.NullOutputStream;
25 import java.io.IOException;
26 import java.io.InputStream;
27 import java.security.DigestInputStream;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30 import java.util.List;
33 * Checksum - simple checksum hashing routines.
37 private static final int BUFFER_SIZE = 32768;
39 public static void update( List<Checksum> checksums, InputStream stream )
42 byte[] buffer = new byte[BUFFER_SIZE];
43 int size = stream.read( buffer, 0, BUFFER_SIZE );
46 for ( Checksum checksum : checksums )
48 checksum.update( buffer, 0, size );
50 size = stream.read( buffer, 0, BUFFER_SIZE );
54 private final MessageDigest md;
56 private ChecksumAlgorithm checksumAlgorithm;
58 public Checksum( ChecksumAlgorithm checksumAlgorithm )
60 this.checksumAlgorithm = checksumAlgorithm;
63 md = MessageDigest.getInstance( checksumAlgorithm.getAlgorithm() );
65 catch ( NoSuchAlgorithmException e )
67 // Not really possible, but here none-the-less
68 throw new IllegalStateException(
69 "Unable to initialize MessageDigest algorithm " + checksumAlgorithm.getAlgorithm() + " : "
70 + e.getMessage(), e );
74 public String getChecksum()
76 return Hex.encode( md.digest() );
79 public ChecksumAlgorithm getAlgorithm()
81 return this.checksumAlgorithm;
89 public Checksum update( byte[] buffer, int offset, int size )
91 md.update( buffer, 0, size );
95 public Checksum update( InputStream stream )
98 try (DigestInputStream dig = new DigestInputStream( stream, md ))
100 IOUtils.copy( dig, new NullOutputStream() );