Created
August 19, 2019 18:21
-
-
Save Ayyagaries/16493db84ab6d26e9db0cfe4a00b4ef8 to your computer and use it in GitHub Desktop.
sample java app
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.MessageDigest; | |
public class Main | |
{ | |
public static void main(String[] args) { | |
System.out.println(hexStringToByteArray(sha256("badge1"))); | |
System.out.println("-------"); | |
System.out.println(byteArrayToHexString(hexStringToByteArray(sha256("badge1")))); | |
System.out.println(byteArrayToHexString(hexStringToByteArray(sha256("badge1")))); | |
} | |
private static String hexToAscii(String hexStr) { | |
StringBuilder output = new StringBuilder(""); | |
for (int i = 0; i < hexStr.length(); i += 2) { | |
String str = hexStr.substring(i, i + 2); | |
output.append((char) Integer.parseInt(str, 16)); | |
} | |
return output.toString(); | |
} | |
public static byte[] hexStringToByteArray(String s) { | |
int len = s.length(); | |
byte[] data = new byte[len / 2]; | |
for (int i = 0; i < len; i += 2) { | |
data[i / 2] = (byte) ((Character.digit(s.charAt(i), 16) << 4) | |
+ Character.digit(s.charAt(i + 1), 16)); | |
} | |
return data; | |
} | |
public static String sha256(String base) { | |
try { | |
MessageDigest digest = MessageDigest.getInstance("SHA-256"); | |
byte[] hash = digest.digest(base.getBytes("UTF-8")); | |
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(); | |
} catch (Exception ex) { | |
throw new RuntimeException(ex); | |
} | |
} | |
public static String byteArrayToHexString(byte[] bytes) { | |
char[] hexArray = "0123456789ABCDEF".toCharArray(); | |
char[] hexChars = new char[bytes.length * 2]; | |
for (int j = 0; j < bytes.length; j++) { | |
int v = bytes[j] & 0xFF; | |
hexChars[j * 2] = hexArray[v >>> 4]; | |
hexChars[j * 2 + 1] = hexArray[v & 0x0F]; | |
} | |
return new String(hexChars); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment