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 {
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 }