Created
September 11, 2020 13:03
-
-
Save SiAust/949b71e8f14c8972de11a56d077f9726 to your computer and use it in GitHub Desktop.
Example hashing using bytes
This file contains 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
class HashingFun { | |
public static void main(String[] args) throws NoSuchAlgorithmException { | |
MessageDigest hasher = MessageDigest.getInstance("SHA-256"); | |
long count = 0; | |
Random random = new Random(); | |
byte[] data = new byte[258 / 8]; | |
while (true) { | |
random.nextBytes(data); | |
byte[] output = hasher.digest(data); | |
count++; | |
// one byte is 2 zeros | |
if (output[0] == 0 && output[1] == 0 /*&& output[2] == 0*/) { | |
System.out.println("Input : " + bytesToString(data)); | |
System.out.println("Output: " + bytesToString(output)); | |
System.out.println("Count: " + count); | |
return; | |
} | |
} | |
} | |
private static String bytesToString(byte[] input) { | |
StringBuilder output = new StringBuilder(); | |
for (byte b : input) { | |
String str = Integer.toHexString(b & 0xFF); | |
if (str.length() == 1) { | |
str = "0" + str; | |
} | |
output.append(str); | |
} | |
return output.toString(); | |
} | |
private static byte[] fromHexString(String input) { | |
ByteArrayOutputStream output = new ByteArrayOutputStream(); | |
for (int i = 0; i < input.length(); i += 2) { | |
int readByte = Integer.parseInt(input.substring(i, i + 2), 16); | |
output.write(readByte & 0xFF); | |
} | |
return output.toByteArray(); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment