Skip to content

Commit

Permalink
Added Hashing cache
Browse files Browse the repository at this point in the history
  • Loading branch information
DHuckaby committed Oct 28, 2012
1 parent 0583083 commit b02449f
Showing 1 changed file with 19 additions and 7 deletions.
26 changes: 19 additions & 7 deletions library/src/com/handlerexploit/common/utils/Hashing.java
Original file line number Diff line number Diff line change
Expand Up @@ -10,23 +10,35 @@
*/
public class Hashing {

private static final char[] hexDigits = "0123456789abcdef".toCharArray();
private static final MessageDigest messageDigest = getMessageDigest("SHA-1");
private static final LruCache<CharSequence, String> CACHE = new LruCache<CharSequence, String>(100);
private static final char[] DIGITS = "0123456789abcdef".toCharArray();
private static final MessageDigest DIGEST = getMessageDigest("SHA-1");

public static String hashString(CharSequence input) {
String hash = CACHE.get(input);
if (hash != null) {
return hash;
}

ByteBuffer scratch = ByteBuffer.allocate(8).order(ByteOrder.LITTLE_ENDIAN);
for (int i = 0; i < input.length(); i++) {
scratch.putChar(input.charAt(i));
messageDigest.update(scratch.array(), 0, Character.SIZE / Byte.SIZE);
DIGEST.update(scratch.array(), 0, Character.SIZE / Byte.SIZE);
scratch.clear();
}

byte[] bytes = messageDigest.digest();
StringBuilder sb = new StringBuilder(2 * bytes.length);
byte[] bytes = DIGEST.digest();
StringBuilder builder = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
sb.append(hexDigits[(b >> 4) & 0xf]).append(hexDigits[b & 0xf]);
builder.append(DIGITS[(b >> 4) & 0xf]).append(DIGITS[b & 0xf]);
}
return sb.toString();
hash = builder.toString();

if (hash != null) {
CACHE.put(input, hash);
}

return hash;
}

private static MessageDigest getMessageDigest(String algorithmName) {
Expand Down

0 comments on commit b02449f

Please sign in to comment.