1 | |
package org.codehaus.plexus.digest; |
2 | |
|
3 | |
|
4 | |
|
5 | |
|
6 | |
|
7 | |
|
8 | |
|
9 | |
|
10 | |
|
11 | |
|
12 | |
|
13 | |
|
14 | |
|
15 | |
|
16 | |
|
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 | |
|
26 | |
|
27 | |
|
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 | 16 | { |
38 | |
try |
39 | |
{ |
40 | 16 | md = MessageDigest.getInstance( algorithm ); |
41 | |
} |
42 | 0 | catch ( NoSuchAlgorithmException e ) |
43 | |
{ |
44 | 0 | throw new IllegalStateException( "Unable to initialize digest algorithm " + algorithm + " : " |
45 | |
+ e.getMessage() ); |
46 | 16 | } |
47 | 16 | } |
48 | |
|
49 | |
public String getAlgorithm() |
50 | |
{ |
51 | 30 | return md.getAlgorithm(); |
52 | |
} |
53 | |
|
54 | |
public String calc() |
55 | |
throws DigesterException |
56 | |
{ |
57 | 28 | return calc( this.md ); |
58 | |
} |
59 | |
|
60 | |
public void reset() |
61 | |
throws DigesterException |
62 | |
{ |
63 | 28 | md.reset(); |
64 | 28 | } |
65 | |
|
66 | |
public void update( InputStream is ) |
67 | |
throws DigesterException |
68 | |
{ |
69 | 28 | update( is, md ); |
70 | 28 | } |
71 | |
|
72 | |
protected static String calc( MessageDigest md ) |
73 | |
{ |
74 | 28 | return Hex.encode( md.digest() ); |
75 | |
} |
76 | |
|
77 | |
protected static void update( InputStream is, MessageDigest digest ) |
78 | |
throws DigesterException |
79 | |
{ |
80 | |
try |
81 | |
{ |
82 | 28 | byte[] buffer = new byte[BUFFER_SIZE]; |
83 | 28 | int size = is.read( buffer, 0, BUFFER_SIZE ); |
84 | 52 | while ( size >= 0 ) |
85 | |
{ |
86 | 24 | digest.update( buffer, 0, size ); |
87 | 24 | size = is.read( buffer, 0, BUFFER_SIZE ); |
88 | |
} |
89 | |
} |
90 | 0 | catch ( IOException e ) |
91 | |
{ |
92 | 0 | throw new DigesterException( "Unable to update " + digest.getAlgorithm() + " hash: " + e.getMessage(), e ); |
93 | 28 | } |
94 | 28 | } |
95 | |
} |