forked from builder-of-web3/HackR_Java_Code
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathJava SHA-256
More file actions
53 lines (45 loc) · 1.44 KB
/
Java SHA-256
File metadata and controls
53 lines (45 loc) · 1.44 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
import java.io.*;
import java.util.*;
import java.text.*;
import java.math.*;
import java.util.regex.*;
import java.security.MessageDigest;
public class Solution {
public static void main(String[] args) {
Scanner sn = new Scanner(System.in);
String data = sn.nextLine();
Solution sj = new Solution();
sj.getSHA256Hash(data);
}
/**
* Returns a hexadecimal encoded SHA-256 hash for the input String.
* @param data
* @return String
*/
private void getSHA256Hash(String data) {
String result = null;
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] hash = digest.digest(data.getBytes("UTF-8"));
bytesToHex(hash);
}catch(Exception ex) {
ex.printStackTrace();
}
}
/**
* Use javax.xml.bind.DatatypeConverter class in JDK to convert byte array
* to a hexadecimal string. Note that this generates hexadecimal in upper case.
* @param hash
* @return
*/
private void bytesToHex(byte[] hash) {
//convert the byte to hex format method 2
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);
}
System.out.println(hexString);
}
}