Skip to content

Instantly share code, notes, and snippets.

@unascribed
Created January 27, 2016 00:19
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save unascribed/5133d4aebb01f083ed06 to your computer and use it in GitHub Desktop.
Save unascribed/5133d4aebb01f083ed06 to your computer and use it in GitHub Desktop.
package whatever;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.util.Random;
import com.google.common.base.Throwables;
import com.google.common.io.BaseEncoding;
public class BrokenDigestTest {
private static final String VALID_CHARACTERS = "qwertyuiopasdfghjklzxcvbnmQWERTYUIOPASDFGHJKLZXCVBNM1234567890_";
public static void main(String[] args) {
char[] arr = new char[16];
Random rand = new Random(System.currentTimeMillis());
System.out.println("Hashing 2000 random strings...");
int fails = 0;
for (int j = 0; j < 2000; j++) {
for (int i = 0; i < arr.length; i++) {
arr[i] = VALID_CHARACTERS.charAt(rand.nextInt(VALID_CHARACTERS.length()));
}
String str = new String(arr);
System.out.print("Hashing "+str+"... ");
String vanilla = hashVanilla(str);
String custom = ServerID.javaHexDigest(str);
String proper = hashProper(str);
if (vanilla.equals(custom)) {
System.out.println("OK");
} else {
fails++;
System.out.println("FAIL");
System.out.println(" Vanilla: "+vanilla);
System.out.println(" ServerID: "+custom);
System.out.println(" Standard: "+proper);
}
}
System.out.println("Done. "+fails+"/2000 failed ("+(int)((fails/2000f)*100)+"% failure rate)");
}
private static String hashVanilla(String str) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(str.getBytes("UTF-8"));
} catch (Exception e) {
throw Throwables.propagate(e);
}
byte[] hash = md.digest();
return new BigInteger(hash).toString(16);
}
private static String hashProper(String str) {
MessageDigest md = null;
try {
md = MessageDigest.getInstance("SHA-1");
md.reset();
md.update(str.getBytes("UTF-8"));
} catch (Exception e) {
throw Throwables.propagate(e);
}
byte[] hash = md.digest();
return BaseEncoding.base16().lowerCase().encode(hash);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment