Simplify Digester utility class.

This commit is contained in:
Luke Taylor 2011-05-25 19:09:08 +01:00
parent 84902ebb50
commit 42e0e158b4
2 changed files with 10 additions and 15 deletions

View File

@ -22,12 +22,12 @@ import java.security.NoSuchProviderException;
/**
* Helper for working with the MessageDigest API.
*
* Performs 1024 iterations of the hashing algorithm per digest to aid in protecting against brute force attacks.
* Performs the configured number of iterations of the hashing algorithm per digest to aid in protecting against brute force attacks.
*
* @author Keith Donald
* @author Luke Taylor
*/
class Digester {
final class Digester {
private final MessageDigest messageDigest;
@ -36,6 +36,7 @@ class Digester {
/**
* Create a new Digester.
* @param algorithm the digest algorithm; for example, "SHA-1" or "SHA-256".
* @param iterations the number of times to apply the digest algorithm to the input
*/
public Digester(String algorithm, int iterations) {
try {
@ -49,16 +50,10 @@ class Digester {
public byte[] digest(byte[] value) {
synchronized (messageDigest) {
for (int i = 0; i < (iterations - 1); i++) {
value = invokeDigest(value);
for (int i = 0; i < iterations; i++) {
value = messageDigest.digest(value);
}
return messageDigest.digest(value);
return value;
}
}
private byte[] invokeDigest(byte[] value) {
messageDigest.reset();
return messageDigest.digest(value);
}
}

View File

@ -14,11 +14,11 @@ import org.springframework.security.crypto.password.Digester;
public class DigesterTests {
@Test
public void digestIsCorrectFor2Iterations() {
Digester digester = new Digester("SHA-1", 2);
public void digestIsCorrectFor3Iterations() {
Digester digester = new Digester("SHA-1", 3);
byte[] result = digester.digest(Utf8.encode("text"));
// echo -n text | openssl sha1 -binary | openssl sha1
assertEquals("cdcefc6a573f294e60e1d633bca3aeba450954a3", new String(Hex.encode(result)));
// echo -n text | openssl sha1 -binary | openssl sha1 -binary | openssl sha1
assertEquals("3cfa28da425eca5b894f0af2b158adf7001e000f", new String(Hex.encode(result)));
}
}