Skip to content

Commit 78724fc

Browse files
committed
fixed hashing algorithm for small segment sizes
1 parent 313edb2 commit 78724fc

File tree

1 file changed

+15
-11
lines changed

1 file changed

+15
-11
lines changed

src/de/ntcomputer/crypto/hash/HashCondenser.java

Lines changed: 15 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -98,7 +98,7 @@ public byte[] compute(InputStream source, long sourceSize) throws IOException, I
9898

9999
// prepare indices
100100
long readSourceSize = 0;
101-
long readSegmentSize = 0;
101+
long previouslyReadSegmentSize = 0;
102102
int readLength = 0;
103103
int segmentIndex = 0;
104104
int resultIndex = 0;
@@ -107,27 +107,31 @@ public byte[] compute(InputStream source, long sourceSize) throws IOException, I
107107
while((readLength = source.read(buf)) != -1) {
108108
readSourceSize+= readLength;
109109
if(readSourceSize > sourceSize) throw new IllegalArgumentException("read more bytes than sourceSize originally provided. Maybe the resource changed?");
110-
readSegmentSize+= readLength;
110+
int readIndex = 0;
111111

112-
if(readSegmentSize < segmentSize) {
113-
// if not enough bytes for one hash(segment) have been accumulated, just update
114-
this.digest.update(buf, 0, readLength);
115-
} else {
112+
// if enough bytes for one hash have been accumulated then calculate the digest now
113+
while(previouslyReadSegmentSize + readLength >= segmentSize) {
116114
// if more bytes than needed have been accumulated, ignore them for now
117-
int limit = (int) (readLength - (readSegmentSize-segmentSize));
115+
int limit = (int) (segmentSize - previouslyReadSegmentSize);
118116

119117
// calculate digest
120-
this.digest.update(buf, 0, limit);
118+
this.digest.update(buf, readIndex, limit);
121119
System.arraycopy(this.digest.digest(), 0, result, resultIndex, digestLength);
122120
resultIndex+= digestLength;
123121

124122
// drop the additional byte from the segmentSize if enough overflowing segments have been processed
125123
segmentIndex++;
126124
if(segmentIndex==overflowSegmentCount) segmentSize--;
127125

128-
// if more bytes than needed have been accumulated, update the next digest now
129-
readSegmentSize = readLength - limit;
130-
if(readSegmentSize > 0) this.digest.update(buf, limit, (int) readSegmentSize);
126+
// mark the bytes as read
127+
previouslyReadSegmentSize = 0;
128+
readLength-= limit;
129+
}
130+
131+
// if not enough bytes for one hash(segment) have been accumulated, just update
132+
if(readLength > 0) {
133+
this.digest.update(buf, readIndex, readLength);
134+
previouslyReadSegmentSize+= readLength;
131135
}
132136
}
133137

0 commit comments

Comments
 (0)