Skip to content

Instantly share code, notes, and snippets.

@cthornton
Created October 25, 2018 22:27
Show Gist options
  • Save cthornton/91b4a0b0e5e60bc837898d8cec884657 to your computer and use it in GitHub Desktop.
Save cthornton/91b4a0b0e5e60bc837898d8cec884657 to your computer and use it in GitHub Desktop.
Hashing
// Example:
//
// System.out.println(Hasher.sha1("hello world")); // prints: 2aae6c35c94fcfb415dbe95f408b9ce91ee846ed
// System.out.println(Hasher.sha1AsInt("hello world")); // prints: 896314922
import java.nio.charset.*;
import com.google.common.hash.*;
class Hasher {
public static String sha1(String input) {
// See https://github.com/google/guava/wiki/HashingExplained
HashFunction hf = Hashing.sha1();
HashCode hc = hf.newHasher()
.putString(input, StandardCharsets.UTF_8)
.hash();
return hc.toString();
}
public static int sha1AsInt(String input) {
HashFunction hf = Hashing.sha1();
HashCode hc = hf.newHasher()
.putString(input, StandardCharsets.UTF_8)
.hash();
return hc.asInt();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment