-
Notifications
You must be signed in to change notification settings - Fork 858
Expand file tree
/
Copy pathJavaSHA256.java
More file actions
42 lines (35 loc) · 935 Bytes
/
Copy pathJavaSHA256.java
File metadata and controls
42 lines (35 loc) · 935 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
30
31
32
33
34
35
36
37
38
39
40
41
42
/**
*
*/
package com.javaaid.hackerrank.solutions.languages.java.advanced;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Scanner;
/**
* @author Kanahaiya Gupta
*
*/
public class JavaSHA256 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String s = sc.next();
System.out.println(getSHAHEX(s));
sc.close();
}
private static String getSHAHEX(String s) {
StringBuffer sb = new StringBuffer();
try {
MessageDigest digest = MessageDigest.getInstance("SHA-256");
byte[] result = digest.digest(s.getBytes());
for (int i = 0; i < result.length; i++) {
String hex = Integer.toHexString(0xff & result[i]);
if (hex.length() == 1)
sb.append('0');
sb.append(hex);
}
} catch (NoSuchAlgorithmException e) {
e.printStackTrace();
}
return sb.toString();
}
}