Skip to content

Commit

Permalink
消息摘要类加入crc32 和 murmurhash
Browse files Browse the repository at this point in the history
  • Loading branch information
calvin1978 committed Nov 14, 2015
1 parent 4b7a491 commit 16e96e6
Show file tree
Hide file tree
Showing 2 changed files with 54 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -17,9 +17,11 @@
import com.google.common.hash.Hashing;

/**
* 支持SHA-1/MD5/CRC32消息摘要的工具类.
* 消息摘要的工具类.
*
* 返回ByteSource,可用Encodes进一步被编码为Hex, Base64或UrlSafeBase64
* 支持SHA-1/MD5这些安全性较高,返回byte[]的(可用Encodes进一步被编码为Hex, Base64或UrlSafeBase64).
*
* 也支持crc32,murmur32这些不追求安全性,性能较高,返回int的.
*
* @author calvin
*/
Expand Down Expand Up @@ -126,11 +128,27 @@ private static byte[] digest(InputStream input, String algorithm) throws IOExcep
}
}

public int crc32(byte[] input) {
public static int crc32(byte[] input) {
return Hashing.crc32().hashBytes(input).asInt();
}

public int crc32(String input) {
public static int crc32(String input) {
return Hashing.crc32().hashString(input, UTF8).asInt();
}

public static int murmur32(byte[] input) {
return Hashing.murmur3_32().hashBytes(input).asInt();
}

public static int murmur32(String input) {
return Hashing.murmur3_32().hashString(input, UTF8).asInt();
}

public static int murmur32(byte[] input, int seed) {
return Hashing.murmur3_32(seed).hashBytes(input).asInt();
}

public static int murmur32(String input, int seed) {
return Hashing.murmur3_32(seed).hashString(input, UTF8).asInt();
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -37,4 +37,36 @@ public void digestFile() throws IOException {
System.out.println("md5: " + Encodes.encodeHex(md5result));
System.out.println("sha1:" + Encodes.encodeHex(sha1result));
}

@Test
public void crc32String() {

String input = "user1";
int result = Digests.crc32(input);
System.out.println("crc32 for user1:" + result);

input = "user2";
result = Digests.crc32(input);
System.out.println("crc32 for user2:" + result);
}

@Test
public void murmurString() {

String input1 = "user1";
int result = Digests.murmur32(input1);
System.out.println("murmur32 for user1:" + result);

String input2 = "user2";
result = Digests.murmur32(input2);
System.out.println("murmur32 for user2:" + result);

int seed = (int) System.currentTimeMillis();
result = Digests.murmur32(input1, seed);
System.out.println("murmur32 with seed for user1:" + result);

result = Digests.murmur32(input2, seed);
System.out.println("murmur32 with seed for user2:" + result);

}
}

0 comments on commit 16e96e6

Please sign in to comment.