Advertisement
Guest User

Password hashing example

a guest
May 9th, 2017
191
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 1.06 KB | None | 0 0
  1. package ass.excercises;
  2.  
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.spec.InvalidKeySpecException;
  5. import java.util.Base64;
  6.  
  7. import javax.crypto.SecretKey;
  8. import javax.crypto.SecretKeyFactory;
  9. import javax.crypto.spec.PBEKeySpec;
  10.  
  11. public class HashingExample {
  12.  
  13.     public static void main(String[] args) {
  14.         System.out.println(hashPassword("pepa", "IOI-655321", "PBKDF2WithHmacSHA1"));
  15.     }
  16.    
  17.     public static String hashPassword(String password, String salt, String algorithm) {
  18.         try {
  19.             PBEKeySpec pbeKeySpec = new PBEKeySpec(password.toCharArray(), salt.getBytes(), 128);
  20.             SecretKeyFactory factory = SecretKeyFactory.getInstance(algorithm);
  21.             SecretKey secret = factory.generateSecret(pbeKeySpec);
  22.             Base64.Encoder enc = Base64.getEncoder();
  23.             return enc.encodeToString(secret.getEncoded());
  24.         } catch (NoSuchAlgorithmException e) {
  25.             throw new IllegalArgumentException("Not a valid encryption algorithm", e);
  26.         } catch (InvalidKeySpecException e) {
  27.             throw new IllegalArgumentException("Not a valid secert key", e);
  28.         }
  29.     }
  30. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement