forked from nayuki/Native-hashes-for-Java
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathBlockHasher.java
More file actions
81 lines (57 loc) · 1.46 KB
/
BlockHasher.java
File metadata and controls
81 lines (57 loc) · 1.46 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
/*
* Native hash functions for Java
*
* Copyright (c) Project Nayuki. (MIT License)
* https://www.nayuki.io/page/native-hash-functions-for-java
*/
package nayuki.nativehash;
public abstract class BlockHasher implements Cloneable {
protected byte[] block;
protected int blockFilled;
protected long length;
public BlockHasher(int blockLen) {
block = new byte[blockLen];
blockFilled = 0;
length = 0;
}
public void update(byte[] b) {
update(b, 0, b.length);
}
public void update(byte[] b, int off, int len) {
int blockLen = block.length;
length += len;
if (blockFilled > 0) {
int n = Math.min(blockLen - blockFilled, len);
System.arraycopy(b, off, block, blockFilled, n);
blockFilled += n;
if (blockFilled == blockLen) {
compress(block, 0, blockLen);
off += n;
len -= n;
} else
return;
}
if (len >= blockLen) {
int n = len / blockLen * blockLen;
compress(b, off, n);
off += n;
len -= n;
}
System.arraycopy(b, off, block, 0, len);
blockFilled = len;
}
public BlockHasher clone() {
try {
BlockHasher result = (BlockHasher)super.clone();
result.block = result.block.clone();
return result;
} catch (CloneNotSupportedException e) {
throw new AssertionError(e);
}
}
public byte[] getHash() {
return clone().getHashDestructively();
}
protected abstract void compress(byte[] msg, int off, int len);
protected abstract byte[] getHashDestructively();
}