Skip to content

Instantly share code, notes, and snippets.

@unascribed
Last active Aug 28, 2021
Embed
What would you like to do?
How to generate a (correct) Minecraft-style hex digest. Tested.
This software is licensed under the CC0 Public Domain Dedication.
See https://creativecommons.org/publicdomain/zero/1.0/ for more details.
package com.unascribed.brokenhash;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.nio.charset.StandardCharsets;
/**
* Generates a broken Minecraft-style twos-complement signed
* hex digest. Tested and confirmed to match vanilla.
*/
public class BrokenHash {
public static String hash(String str) {
try {
byte[] digest = digest(str, "SHA-1");
return new BigInteger(digest).toString(16);
} catch (NoSuchAlgorithmException e) {
throw new RuntimeException(e);
}
}
private static byte[] digest(String str, String algorithm) throws NoSuchAlgorithmException {
MessageDigest md = MessageDigest.getInstance(algorithm);
byte[] strBytes = str.getBytes(StandardCharsets.UTF_8);
return md.digest(strBytes);
}
}
@GramDev1

This comment has been minimized.

Copy link

@GramDev1 GramDev1 commented Aug 22, 2016

do u need the server id for this

@deprilula28

This comment has been minimized.

Copy link

@deprilula28 deprilula28 commented Aug 23, 2016

Can you give the benchmark numbers? Did I miss them?

Thanks

@unascribed

This comment has been minimized.

Copy link
Owner Author

@unascribed unascribed commented Mar 14, 2017

Gist apparently doesn't notify me when comments are posted. 😠

@mcjp78 - No, the server ID is always blank in recent versions of Minecraft.

@deprilula28 - Sure; note that I've upgraded my hardware since I wrote this originally:

Generating workset... 200/2000
Warming up... Done
GCing... Done
Benchmarking Method #1... Done in 4.405 s (avg 88095.63ns per run)
GCing... Done
Benchmarking Method #2... Done in 2.172 s (avg 43447.664ns per run)

Both methods are very fast and there is no reason to use MethodTwo. I wrote it to learn how twos-complement and such works.

Also note that I have learned since I wrote this that the method I use to benchmark is fundamentally broken. I should have used an existing microbenchmark library, but I didn't, and as a result the test sucks and isn't really meaningful.

EDIT: I've removed the second method and the benchmark from the Gist.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment