-
Notifications
You must be signed in to change notification settings - Fork 0
/
javaSHA-256.java
50 lines (39 loc) · 1.47 KB
/
javaSHA-256.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
import java.io.*;
import java.util.*;
import java.math.BigInteger;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
public class Solution {
public static byte[] getSHA(String input) throws NoSuchAlgorithmException
{
MessageDigest md = MessageDigest.getInstance("SHA-256");
return md.digest(input.getBytes(StandardCharsets.UTF_8));
}
public static String toHexString(byte[] hash)
{
// Convert byte array into signum representation
BigInteger number = new BigInteger(1, hash);
// Convert message digest into hex value
StringBuilder hexString = new StringBuilder(number.toString(16));
// Pad with leading zeros
while (hexString.length() < 64)
{
hexString.insert(0, '0');
}
return hexString.toString();
}
public static void main(String[] args) {
/* Enter your code here. Read input from STDIN. Print output to STDOUT. Your class should be named Solution. */
try
{
Scanner sc = new Scanner(System.in);
String s2= sc.nextLine();
System.out.println(toHexString(getSHA(s2)));
}
catch (NoSuchAlgorithmException e) {
System.out.println("Exception thrown for incorrect algorithm: " + e);
}
}
}