-
Notifications
You must be signed in to change notification settings - Fork 0
/
Merkle.java~
77 lines (67 loc) · 2.2 KB
/
Merkle.java~
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
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.List;
public class Merkle {
public static MessageDigest md;
public static void main(String[] args) throws NoSuchAlgorithmException {
md = MessageDigest.getInstance("SHA-256");
String a = "a";
byte[] a_dHashBytes = dHash(a);
System.out.println( bitsToHex(a_dHashBytes));
String five = "five";
byte[] five_dHashBytes = dHash(five);
System.out.println( bitsToHex(five_dHashBytes));
byte[] a_five_concat = new byte[a_dHashBytes.length * 2];
System.arraycopy(a_dHashBytes, 0, a_five_concat, 0, a_dHashBytes.length);
System.arraycopy(five_dHashBytes, 0, a_five_concat, a_dHashBytes.length, five_dHashBytes.length);
byte[] concatHash = dHash(a_five_concat);
System.out.println(bitsToHex(concatHash));
String[] input = {"a", "five", "word", "input", "example"};
System.out.println(calcMerkleRoot(input));
}
public static byte[] dHash(byte[] val) {
md.update(val);
md.update(md.digest());
return md.digest();
}
public static byte[] dHash(String val) {
md.update(val.getBytes());
md.update(md.digest());
return md.digest();
}
public static String bitsToHex(byte[] byteArray) {
StringBuffer result = new StringBuffer();
for (byte b:byteArray) {
result.append(String.format("%02x", b));
}
return result.toString();
}
public static String calcMerkleRoot(String[] input) {
List<byte[]> start = new ArrayList<byte[]>();
for (int j = 0; j < input.length; j++) {
start.add(dHash(input[j]));
}
while (start.size() != 1) {
if (start.size() % 2 == 1) {
start.add(start.get(start.size() - 1));
}
List<byte[]> next = new ArrayList<byte[]>();
for (int i = 0; i < start.size(); i += 2) {
next.add(dHash(concatHash(start.get(i), start.get(i + 1))));
}
start = next;
}
return bitsToHex(start.get(0));
}
// only use this if a and b have the same length
public static byte[] concatHash(byte[] a, byte[] b) {
if (a.length != b.length) {
throw new IllegalArgumentException();
}
byte[] c = new byte[a.length * 2];
System.arraycopy(a, 0, c, 0, a.length);
System.arraycopy(b, 0, c, b.length, a.length);
return c;
}
}