-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHashUtility.java
More file actions
37 lines (31 loc) · 1.17 KB
/
Copy pathHashUtility.java
File metadata and controls
37 lines (31 loc) · 1.17 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
package blockchain;
import java.security.MessageDigest;
import java.util.Random;
public class HashUtility {
public static long generateMagicNumber(String zeros) {
String hash;
long magicNumber = System.currentTimeMillis();
do {
magicNumber = Math.abs(magicNumber / 3 + (long)
(new Random().nextInt() * Math.random()));
hash = HashUtility.applySha256(String.valueOf(magicNumber));
} while (!hash.startsWith(zeros));
return magicNumber;
}
public static String applySha256(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
/* Applies sha256 to our input */
StringBuilder hexString = new StringBuilder();
byte[] hash = digest.digest(input.getBytes("UTF-8"));
for (byte elem : hash) {
String hex = Integer.toHexString(0xff & elem);
if (hex.length() == 1) hexString.append('0');
hexString.append(hex);
}
return hexString.toString();
} catch (Exception e) {
throw new RuntimeException(e);
}
}
}