Skip to content

Instantly share code, notes, and snippets.

@dragansah
Created October 20, 2011 17:24
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/1301719 to your computer and use it in GitHub Desktop.
Save dragansah/1301719 to your computer and use it in GitHub Desktop.
package com.plannow.highedu.services.impl;
import static org.junit.Assert.*;
import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Arrays;
import org.apache.commons.codec.binary.Base64;
import org.junit.Test;
public class TestEncryption
{
private static final int ITERATION_NUMBER = 1000;
public static String getPasswordHash(String salt, String password)
{
try
{
byte[] hashedPassword = getHash(ITERATION_NUMBER, password, base64ToByte(salt));
return byteToBase64(hashedPassword);
}
catch (NoSuchAlgorithmException e)
{
e.printStackTrace();
}
catch (UnsupportedEncodingException e)
{
e.printStackTrace();
}
return null;
}
/**
* 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());
}
@Test
public void test1() throws NoSuchAlgorithmException, UnsupportedEncodingException
{
// Encrypt part
byte[] hash = getHash(ITERATION_NUMBER, "mypassword", base64ToByte("mysalt"));
// this string should be stored in the database
String hashString = byteToBase64(hash);
// Check Part
String salt = "mysalt"; // read the salt from the database
String hashFromDB = hashString; // read the hash string from the database
byte[] hashDigest = base64ToByte(hashFromDB);
byte[] saltDigest = base64ToByte(salt);
byte[] proposedDigest = getHash(ITERATION_NUMBER, "mypassword", saltDigest);
assertTrue(Arrays.equals(proposedDigest, hashDigest));
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment