This project has retired. For details please refer to its
Attic page.
Checksum xref
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.nio.ByteBuffer;
24 import java.nio.MappedByteBuffer;
25 import java.nio.channels.FileChannel;
26 import java.nio.file.Path;
27 import java.nio.file.StandardOpenOption;
28 import java.security.MessageDigest;
29 import java.security.NoSuchAlgorithmException;
30
31
32
33
34 public class Checksum
35 {
36 private byte[] result = new byte[0];
37
38 private final MessageDigest md;
39
40 private ChecksumAlgorithm checksumAlgorithm;
41
42 public Checksum( ChecksumAlgorithm checksumAlgorithm )
43 {
44 this.checksumAlgorithm = checksumAlgorithm;
45 try
46 {
47 md = MessageDigest.getInstance( checksumAlgorithm.getAlgorithm() );
48 }
49 catch ( NoSuchAlgorithmException e )
50 {
51
52 throw new IllegalStateException(
53 "Unable to initialize MessageDigest algorithm " + checksumAlgorithm.getAlgorithm() + " : "
54 + e.getMessage(), e );
55 }
56 }
57
58 public String getChecksum()
59 {
60 if (this.result.length==0) {
61 finish();
62 }
63 return Hex.encode( this.result );
64 }
65
66 public byte[] getChecksumBytes() {
67 if (this.result.length==0) {
68 finish();
69 }
70 return this.result;
71 }
72
73 public ChecksumAlgorithm getAlgorithm()
74 {
75 return this.checksumAlgorithm;
76 }
77
78 public void reset()
79 {
80 md.reset();
81 this.result = new byte[0];
82 }
83
84 public Checksum update( byte[] buffer, int offset, int size )
85 {
86 if (this.result.length!=0) {
87 reset();
88 }
89 md.update( buffer, 0, size );
90 return this;
91 }
92
93 public Checksum update( ByteBuffer buffer)
94 {
95 if (this.result.length!=0) {
96 reset();
97 }
98 md.update( buffer );
99 return this;
100 }
101
102 public Checksum finish() {
103 this.result = md.digest();
104 return this;
105 }
106
107 public boolean compare(byte[] cmp) {
108 if (this.result == null || this.result.length==0) {
109 finish();
110 }
111 return md.isEqual( this.result, cmp );
112 }
113
114 public boolean compare(String hexString) {
115 if (this.result == null || this.result.length==0) {
116 finish();
117 }
118 return md.isEqual(this.result, Hex.decode( hexString ));
119 }
120 }