Skip to content

Instantly share code, notes, and snippets.

@davinchia
Created December 7, 2018 01:50
Show Gist options
  • Save davinchia/1570e827fd7faa320ebb7b77e4f0e5b4 to your computer and use it in GitHub Desktop.
Save davinchia/1570e827fd7faa320ebb7b77e4f0e5b4 to your computer and use it in GitHub Desktop.
Google Hashing Transformation flow.
// Testing main method.
public static void main(String[] args) throws Exception {
String firstID = "491d69e08dbdaeacbed17194761f97b1b9c9a3928e7c3b1b0add760a37a45b4d";
String salt = "DPK54AN4HZE4N9G0D4RC2EOH8A58H1Z6";
String answer = "71e10f9d4ab22a8c0a31ec27c8913a13a12a5ebb6500baaaea9a9bd694447cc1";
// Only do second transformation
// 1. Hex decode |firstID|.
// 3. Prefix |salt| to |base|.
// 4. SHA256 hash.
// 5. Return hex encoded hash.
byte[] base = Hex.decodeHex(firstID.toCharArray()); // hex decode
HashTransformation secondTransform = new HashTransformation(HashTransformation.Type.SHA256,
salt, true);
// Prefix, hash, and hex encode.
System.out.println(secondTransform.transform(new String(base)));
// This gives 73165e3e19523ea84ffdc2b338248f0c7c5d47f672703f4cb7885537b9a4f559.
}
// Parts of the HashTransformation class.
public HashTransformation(Type type, byte[] salt, boolean hexEncode) {
this.type = type;
this.salt = salt;
this.hexEncode = hexEncode;
}
@Override
public String transform(String value) {
byte[] hashedBytes;
switch (type) {
case MD5:
hashedBytes = DigestUtils.md5(prefixSalt(value));
break;
case SHA1:
hashedBytes = DigestUtils.sha(prefixSalt(value));
break;
case SHA256:
hashedBytes = DigestUtils.sha256(prefixSalt(value));
break;
default:
throw new NotImplementedException("Unsupported hash " + type);
}
return hexEncode ? Hex.encodeHexString(hashedBytes) : Strings.fromBytes(hashedBytes);
}
private byte[] prefixSalt(String value) {
return Bytes.concat(salt, Strings.toBytes(value));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment