/*
 * Copyright 2011-2016 the original author or authors.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.springframework.security.crypto.password;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * Helper for working with the MessageDigest API.
 *
 * 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
 */
final class Digester {

	private final String algorithm;

	private final int iterations;

	/**
	 * 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) {
		// eagerly validate the algorithm
		createDigest(algorithm);
		this.algorithm = algorithm;
		this.iterations = iterations;
	}

	public byte[] digest(byte[] value) {
		MessageDigest messageDigest = createDigest(algorithm);
		for (int i = 0; i < iterations; i++) {
			value = messageDigest.digest(value);
		}
		return value;
	}

	private static MessageDigest createDigest(String algorithm) {
		try {
			return MessageDigest.getInstance(algorithm);
		}
		catch (NoSuchAlgorithmException e) {
			throw new IllegalStateException("No such hashing algorithm", e);
		}
	}
}

@@ -1068,22 +1068,16 @@
 private 
-final 
 int iter
@@ -1084,16 +1084,16 @@
 ations;%0A
+
 %0A%09/**%0A%09 
@@ -1437,14 +1437,12 @@
 ;%0A%09%09
-this.i
+setI
 tera
@@ -1446,19 +1446,17 @@
 erations
- = 
+(
 iteratio
@@ -1457,16 +1457,17 @@
 erations
+)
 ;%0A%09%7D%0A%0A%09p
@@ -1644,16 +1644,16 @@
 e);%0A%09%09%7D%0A
-
 %09%09return
@@ -1664,16 +1664,209 @@
 ue;%0A%09%7D%0A%0A
+%09final void setIterations(int iterations) %7B%0A%09%09if(iterations %3C= 0) %7B%0A%09%09%09throw new IllegalArgumentException(%22Iterations value must be greater than zero%22);%0A%09%09%7D%0A%09%09this.iterations = iterations;%0A%09%7D%0A%0A
 %09private

Allow Digester iterations to update