Created
January 1, 2013 08:02
-
-
Save andrewrk/4425843 to your computer and use it in GitHub Desktop.
how to generate minecraft hex digests
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
var crypto = require('crypto'); | |
var assert = require('assert'); | |
function mcHexDigest(str) { | |
var hash = new Buffer(crypto.createHash('sha1').update(str).digest(), 'binary'); | |
// check for negative hashes | |
var negative = hash.readInt8(0) < 0; | |
if (negative) performTwosCompliment(hash); | |
var digest = hash.toString('hex'); | |
// trim leading zeroes | |
digest = digest.replace(/^0+/g, ''); | |
if (negative) digest = '-' + digest; | |
return digest; | |
} | |
function performTwosCompliment(buffer) { | |
var carry = true; | |
var i, newByte, value; | |
for (i = buffer.length - 1; i >= 0; --i) { | |
value = buffer.readUInt8(i); | |
newByte = ~value & 0xff; | |
if (carry) { | |
carry = newByte === 0xff; | |
buffer.writeUInt8(newByte + 1, i); | |
} else { | |
buffer.writeUInt8(newByte, i); | |
} | |
} | |
} | |
assert.strictEqual(mcHexDigest('Notch'), "4ed1f46bbe04bc756bcb17c0c7ce3e4632f06a48"); | |
assert.strictEqual(mcHexDigest('jeb_'), "-7c9d5b0044c130109a5d7b5fb5c317c02b4e28c1"); | |
assert.strictEqual(mcHexDigest('simon'), "88e16a1019277b15d58faf0541e11910eb756f6"); |
This is much simpler using modern javascript:
function hexDigest(text) {
const hash = crypto.createHash("sha1")
.update(text)
.digest()
return BigInt.asIntN( // performs two's compliment
160, // hash size in bits
hash.reduce( // convert buffer to bigint using reduce
(a, x) =>
a << 8n | // bit-shift the accumulator 8 bits (one byte) to the left
BigInt(x), // fill lower byte just freed up by bit-shifting using bitwise or-operator
0n // start with accumulator value of 0
)
).toString(16) // display the result with base 16 (hex)
}
Apparently, you can do this, which is much simpler to read and also internally optimized (unlike the bitwise or reduce approach):
BigInt(`0x${digest.toString('hex')}`)
So we get this, and I'm fine with how it looks:
export function minecraftSha1(
serverId: string,
sharedSecret: Buffer,
publicKey: Buffer,
): string {
const sha1 = createHash('sha1');
sha1.update(Buffer.from(serverId, 'ascii'));
sha1.update(sharedSecret);
sha1.update(publicKey);
return mcHexDigest(sha1.digest());
}
function mcHexDigest(digest: Buffer | Uint8Array): string {
const bigint = BigInt(`0x${digest.toString('hex')}`);
return BigInt.asIntN(digest.length * 8, bigint).toString(16);
}
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Replying to timvandam
I smell ECMAscript... delicious!