Created
May 30, 2017 10:47
-
-
Save KCSOPHEAK/a5286aa7d485fca2396991acf686d76b to your computer and use it in GitHub Desktop.
PBKDF2 Implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import java.security.NoSuchAlgorithmException; | |
import java.security.SecureRandom; | |
import java.security.spec.InvalidKeySpecException; | |
import java.security.spec.KeySpec; | |
import java.util.Arrays; | |
import javax.crypto.SecretKeyFactory; | |
import javax.crypto.spec.PBEKeySpec; | |
public class PasswordEncryptionService { | |
public boolean authenticate(String attemptedPassword, byte[] encryptedPassword, byte[] salt) | |
throws NoSuchAlgorithmException, InvalidKeySpecException { | |
byte[] encryptedAttemptedPassword = getEncryptedPassword(attemptedPassword, salt); | |
return Arrays.equals(encryptedPassword, encryptedAttemptedPassword); | |
} | |
public byte[] getEncryptedPassword(String password, byte[] salt) | |
throws NoSuchAlgorithmException, InvalidKeySpecException { | |
String algorithm = "PBKDF2WithHmacSHA1"; | |
int derivedKeyLength = 160; | |
int iterations = 20000; | |
KeySpec spec = new PBEKeySpec(password.toCharArray(), salt, iterations, derivedKeyLength); | |
SecretKeyFactory f = SecretKeyFactory.getInstance(algorithm); | |
return f.generateSecret(spec).getEncoded(); | |
} | |
public byte[] generateSalt() throws NoSuchAlgorithmException { | |
SecureRandom random = SecureRandom.getInstance("SHA1PRNG"); | |
byte[] salt = new byte[8]; | |
random.nextBytes(salt); | |
return salt; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment