Chiddix

Salt

Sep 12th, 2013
161
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.07 KB | None | 0 0
  1. import java.io.UnsupportedEncodingException;
  2. import java.security.MessageDigest;
  3. import java.security.NoSuchAlgorithmException;
  4.  
  5. /**
  6.  * @author Ryan Greene
  7.  *
  8.  */
  9. public final class Salt {
  10.  
  11.     /**
  12.      * The message digest instance.
  13.      */
  14.     private final MessageDigest messageDigest;
  15.  
  16.     /**
  17.      * The amount of iterations which the salt is applied.
  18.      */
  19.     private final int iterations;
  20.  
  21.     /**
  22.      * The salt being applied.
  23.      */
  24.     private final byte[] salt;
  25.  
  26.     /**
  27.      * Creates a new salt instance with the specified amount of iterations and
  28.      * salt.
  29.      *
  30.      * @param iterations The amount of iterations which the salt is applied.
  31.      * @param salt The salt being applied.
  32.      * @return The created salt instance.
  33.      */
  34.     public static final Salt create(final int iterations, final byte[] salt) throws NoSuchAlgorithmException {
  35.         return new Salt(MessageDigest.getInstance("SHA-1"), iterations, salt);
  36.     }
  37.  
  38.     /**
  39.      * Constructs a new salt instance with the specified message digest, amount
  40.      * of iterations and salt.
  41.      *
  42.      * @param messageDigest The message digest instance.
  43.      * @param iterations The amount of iterations which the salt is applied.
  44.      * @param salt The salt being applied.
  45.      */
  46.     private Salt(final MessageDigest messageDigest, final int iterations, final byte[] salt) {
  47.         this.messageDigest = messageDigest;
  48.         this.iterations = iterations;
  49.         this.salt = salt;
  50.     }
  51.  
  52.     /**
  53.      * Hashes and applies salt to the specified password.
  54.      *
  55.      * @param password The password being hashed.
  56.      * @return The hashed and salted password.
  57.      * @throws NoSuchAlgorithmException If an exception is thrown.
  58.      * @throws UnsupportedEncodingException If an exception is thrown.
  59.      */
  60.     public final byte[] applySalt(final String password) throws NoSuchAlgorithmException, UnsupportedEncodingException {
  61.         messageDigest.reset();
  62.         messageDigest.update(salt);
  63.         byte[] input = messageDigest.digest(password.getBytes("UTF-8"));
  64.         for (int iteration = 0; iteration < iterations; iteration++) {
  65.             messageDigest.reset();
  66.             input = messageDigest.digest(input);
  67.         }
  68.         return input;
  69.     }
  70. }
Advertisement
Add Comment
Please, Sign In to add comment