Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.io.UnsupportedEncodingException;
- import java.security.MessageDigest;
- import java.security.NoSuchAlgorithmException;
- /**
- * @author Ryan Greene
- *
- */
- public final class Salt {
- /**
- * The message digest instance.
- */
- private final MessageDigest messageDigest;
- /**
- * The amount of iterations which the salt is applied.
- */
- private final int iterations;
- /**
- * The salt being applied.
- */
- private final byte[] salt;
- /**
- * Creates a new salt instance with the specified amount of iterations and
- * salt.
- *
- * @param iterations The amount of iterations which the salt is applied.
- * @param salt The salt being applied.
- * @return The created salt instance.
- */
- public static final Salt create(final int iterations, final byte[] salt) throws NoSuchAlgorithmException {
- return new Salt(MessageDigest.getInstance("SHA-1"), iterations, salt);
- }
- /**
- * Constructs a new salt instance with the specified message digest, amount
- * of iterations and salt.
- *
- * @param messageDigest The message digest instance.
- * @param iterations The amount of iterations which the salt is applied.
- * @param salt The salt being applied.
- */
- private Salt(final MessageDigest messageDigest, final int iterations, final byte[] salt) {
- this.messageDigest = messageDigest;
- this.iterations = iterations;
- this.salt = salt;
- }
- /**
- * Hashes and applies salt to the specified password.
- *
- * @param password The password being hashed.
- * @return The hashed and salted password.
- * @throws NoSuchAlgorithmException If an exception is thrown.
- * @throws UnsupportedEncodingException If an exception is thrown.
- */
- public final byte[] applySalt(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
- messageDigest.reset();
- messageDigest.update(salt);
- byte[] input = messageDigest.digest(password.getBytes("UTF-8"));
- for (int iteration = 0; iteration < iterations; iteration++) {
- messageDigest.reset();
- input = messageDigest.digest(input);
- }
- return input;
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment