Skip to content

Instantly share code, notes, and snippets.

@dragansah
Created October 8, 2011 10:50
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save dragansah/1272132 to your computer and use it in GitHub Desktop.
Save dragansah/1272132 to your computer and use it in GitHub Desktop.
private static final int ITERATION_NUMBER = 1000;
public boolean authenticate(String username, String password)
{
User user = (User) getSession().createCriteria(User.class).add(Restrictions.eq("email", username))
.uniqueResult();
if (user == null)
return false;
String passwordHash = user.getPasswordHash();
String salt = user.getSalt();
try
{ // Use Base 64 encoding
byte[] bDigest = base64ToByte(passwordHash);
byte[] bSalt = base64ToByte(salt);
// Compute the new DIGEST
byte[] proposedDigest = getHash(ITERATION_NUMBER, password, bSalt);
if (!Arrays.equals(proposedDigest, bDigest))
{
/*
* If a user which is currently logged in fails to authenticate then log him out !
*/
logout();
return false;
}
login(user);
return true;
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
return false;
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
return false;
}
}
/**
* From a password, a number of iterations and a salt, returns the corresponding digest
*
* @param iterationNb
* The number of iterations of the algorithm
* @param password
* The password to encrypt
* @param salt
* The salt
* @return The digested password
* @throws NoSuchAlgorithmException
* If the algorithm doesn't exist
* @throws UnsupportedEncodingException
*/
public static byte[] getHash(int iterationNb, String password, byte[] salt) throws NoSuchAlgorithmException,
UnsupportedEncodingException
{
MessageDigest digest = MessageDigest.getInstance("SHA-1");
digest.reset();
digest.update(salt);
byte[] input = digest.digest(password.getBytes("UTF-8"));
for (int i = 0; i < iterationNb; i++)
{
digest.reset();
input = digest.digest(input);
}
return input;
}
public static String byteToBase64(byte[] data)
{
return new String(new Base64().encode(data));
}
public static byte[] base64ToByte(String data)
{
return new Base64().decode(data.getBytes());
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment