Skip to content

Instantly share code, notes, and snippets.

@JustinTArthur
Last active June 28, 2017 21:17
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save JustinTArthur/3528cfca7e644547d6ce to your computer and use it in GitHub Desktop.
Save JustinTArthur/3528cfca7e644547d6ce to your computer and use it in GitHub Desktop.
Java for checking the password of a user against a typical Django user table entry
// Assumes an encoded password entry that looks like:
// pbkdf2_sha256$13000$I2fysbVVZ$6WuU/biq8RveLuiTgpLeEJ7hcqoqpkqVlpUIHWUoi9I=
String[] encodedPassword = passedInPassword.split("\\$");
int encodedIterations = Integer.parseInt(encodedPassword[1]);
byte[] encodedSalt = encodedPassword[2].getBytes(Charset.forName("UTF-8"));
String encodedHash = encodedPassword[3];
SecretKeyFactory f = null;
try {
f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
} catch (NoSuchAlgorithmException e) {
System.out.println("Need a Java implementation with cryptography.");
}
KeySpec ks = new PBEKeySpec(passedInPassword.toCharArray(), encodedSalt, encodedIterations, 256);
SecretKey s = null;
try {
s = f.generateSecret(ks);
} catch (InvalidKeySpecException e) {
System.out.println("Encoded password is corrupt.");
}
if (encodedHash.equals(Base64.getEncoder().encodeToString(s.getEncoded()))) {
System.out.println("User is legit.");
} else {
System.out.println("Passed in password is not correct.");
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment