Advertisement
Guest User

PassUtils

a guest
Mar 29th, 2020
82
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 2.05 KB | None | 0 0
  1. package pl.wodamuszyna.auth.utils;
  2.  
  3. import java.security.NoSuchAlgorithmException;
  4. import java.security.SecureRandom;
  5. import java.security.spec.InvalidKeySpecException;
  6. import java.util.Arrays;
  7. import java.util.Base64;
  8. import java.util.Optional;
  9.  
  10. import javax.crypto.SecretKeyFactory;
  11. import javax.crypto.spec.PBEKeySpec;
  12.  
  13. public class PassUtils {
  14.  
  15. //najpierw generujesz salta funkcją generateSalt o długości np. 32 i wpisujesz go jako zmienna salt a potem już hashujesz hasła razem z //saltem i weryfikujesz bo nie da się ich odhashować
  16.  
  17.     private static final SecureRandom RAND = new SecureRandom();
  18.     private static final int ITERATIONS = 65536;
  19.     private static final int KEY_LENGTH = 512;
  20.     private static final String ALGORITHM = "PBKDF2WithHmacSHA512";
  21.     public static final String salt = "";
  22.    
  23.     public static Optional<String> generateSalt (final int length){
  24.        
  25.         if(length < 1) {
  26.             System.err.println("salt must be > 0");
  27.             return Optional.empty();
  28.         }
  29.        
  30.         byte[] salt = new byte[length];
  31.         RAND.nextBytes(salt);
  32.        
  33.         return Optional.of(Base64.getEncoder().encodeToString(salt));
  34.     }
  35.    
  36.     public static Optional<String> hashPassword (String password, String salt){
  37.        
  38.         char[] chars = password.toCharArray();
  39.         byte[] bytes = salt.getBytes();
  40.        
  41.         PBEKeySpec spec = new PBEKeySpec(chars, bytes, ITERATIONS, KEY_LENGTH);
  42.        
  43.         Arrays.fill(chars, Character.MIN_VALUE);
  44.        
  45.         try {
  46.             SecretKeyFactory fac = SecretKeyFactory.getInstance(ALGORITHM);
  47.             byte[] securePassword = fac.generateSecret(spec).getEncoded();
  48.             return Optional.of(Base64.getEncoder().encodeToString(securePassword));
  49.            
  50.         }catch(NoSuchAlgorithmException | InvalidKeySpecException ex) {
  51.             System.err.println("Exception ocurred");
  52.             return Optional.empty();
  53.         }finally {
  54.             spec.clearPassword();
  55.         }
  56.        
  57.     }
  58.    
  59.     public static boolean verifyPassword (String password, String key, String salt) {
  60.         Optional<String> optEncrypted = hashPassword(password, salt);
  61.         if(!optEncrypted.isPresent()) return false;
  62.         return optEncrypted.get().equals(key);
  63.     }
  64.    
  65.    
  66. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement