1 | |
package org.apache.archiva.checksum; |
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
17 | |
|
18 | |
|
19 | |
|
20 | |
|
21 | |
|
22 | |
import java.io.IOException; |
23 | |
import java.io.InputStream; |
24 | |
import java.security.DigestInputStream; |
25 | |
import java.security.MessageDigest; |
26 | |
import java.security.NoSuchAlgorithmException; |
27 | |
import java.util.List; |
28 | |
|
29 | |
import org.apache.commons.io.IOUtils; |
30 | |
import org.apache.commons.io.output.NullOutputStream; |
31 | |
|
32 | |
|
33 | |
|
34 | |
|
35 | |
|
36 | |
|
37 | |
public class Checksum |
38 | |
{ |
39 | |
private static final int BUFFER_SIZE = 32768; |
40 | |
|
41 | |
public static void update( List<Checksum> checksums, InputStream stream ) |
42 | |
throws IOException |
43 | |
{ |
44 | 0 | byte[] buffer = new byte[BUFFER_SIZE]; |
45 | 0 | int size = stream.read( buffer, 0, BUFFER_SIZE ); |
46 | 0 | while ( size >= 0 ) |
47 | |
{ |
48 | 0 | for ( Checksum checksum : checksums ) |
49 | |
{ |
50 | 0 | checksum.update( buffer, 0, size ); |
51 | |
} |
52 | 0 | size = stream.read( buffer, 0, BUFFER_SIZE ); |
53 | |
} |
54 | 0 | } |
55 | |
|
56 | |
protected final MessageDigest md; |
57 | |
|
58 | |
private ChecksumAlgorithm checksumAlgorithm; |
59 | |
|
60 | |
public Checksum( ChecksumAlgorithm checksumAlgorithm ) |
61 | 0 | { |
62 | 0 | this.checksumAlgorithm = checksumAlgorithm; |
63 | |
try |
64 | |
{ |
65 | 0 | md = MessageDigest.getInstance( checksumAlgorithm.getAlgorithm() ); |
66 | |
} |
67 | 0 | catch ( NoSuchAlgorithmException e ) |
68 | |
{ |
69 | |
|
70 | 0 | throw new IllegalStateException( "Unable to initialize MessageDigest algorithm " + checksumAlgorithm.getAlgorithm() |
71 | |
+ " : " + e.getMessage(), e ); |
72 | 0 | } |
73 | 0 | } |
74 | |
|
75 | |
public String getChecksum() |
76 | |
{ |
77 | 0 | return Hex.encode( md.digest() ); |
78 | |
} |
79 | |
|
80 | |
public ChecksumAlgorithm getAlgorithm() |
81 | |
{ |
82 | 0 | return this.checksumAlgorithm; |
83 | |
} |
84 | |
|
85 | |
public void reset() |
86 | |
{ |
87 | 0 | md.reset(); |
88 | 0 | } |
89 | |
|
90 | |
public Checksum update( byte[] buffer, int offset, int size ) |
91 | |
{ |
92 | 0 | md.update( buffer, 0, size ); |
93 | 0 | return this; |
94 | |
} |
95 | |
|
96 | |
public Checksum update( InputStream stream ) |
97 | |
throws IOException |
98 | |
{ |
99 | 0 | DigestInputStream dig = new DigestInputStream( stream, md ); |
100 | 0 | IOUtils.copy( dig, new NullOutputStream() ); |
101 | |
|
102 | 0 | return this; |
103 | |
} |
104 | |
} |