-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathToHash.java
More file actions
29 lines (26 loc) · 893 Bytes
/
ToHash.java
File metadata and controls
29 lines (26 loc) · 893 Bytes
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
// https://www.quickprogrammingtips.com/java/how-to-generate-sha256-hash-in-java.html
// Class to create a SHA256 hash to a String
import java.security.MessageDigest;
public class ToHash {
public static String applyHash(String input) {
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(input.getBytes("UTF-8"));
return bytesToHex(hash);
} catch (Exception e) {
throw new RuntimeException(e);
}
}
// Converting the hash to a String
private static String bytesToHex(byte[] hash) {
StringBuffer hexString = new StringBuffer();
for (int i = 0; i < hash.length; i++) {
String hex = Integer.toHexString(0xff & hash[i]);
if (hex.length() == 1) {
hexString.append('0');
}
hexString.append(hex);
}
return hexString.toString();
}
}