Skip to content

Commit cef0fda

Browse files
committed
Add SHA1 hasher class
1 parent 4099268 commit cef0fda

File tree

2 files changed

+40
-0
lines changed

2 files changed

+40
-0
lines changed
Lines changed: 25 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,25 @@
1+
package httpserver;
2+
3+
import java.security.MessageDigest;
4+
import java.security.NoSuchAlgorithmException;
5+
6+
public class Hasher {
7+
public String getHash(byte[] input) {
8+
MessageDigest messageDigest = null;
9+
try {
10+
messageDigest = MessageDigest.getInstance("SHA1");
11+
} catch (NoSuchAlgorithmException e) {
12+
e.printStackTrace();
13+
}
14+
byte[] hash = messageDigest.digest(input);
15+
return bytesToHex(hash);
16+
}
17+
18+
private String bytesToHex(byte[] hash) {
19+
StringBuffer stringBuffer = new StringBuffer();
20+
for (byte b : hash) {
21+
stringBuffer.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
22+
}
23+
return stringBuffer.toString();
24+
}
25+
}
Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,15 @@
1+
package httpserver;
2+
3+
import org.junit.Test;
4+
5+
import static org.junit.Assert.*;
6+
7+
public class HasherTest {
8+
@Test
9+
public void returnsHashForBytes() throws Exception {
10+
Hasher hasher = new Hasher();
11+
byte[] input = "default content".getBytes();
12+
assertEquals("dc50a0d27dda2eee9f65644cd7e4c9cf11de8bec",
13+
hasher.getHash(input));
14+
}
15+
}

0 commit comments

Comments
 (0)