Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
The hmac+bcrypt password storage for Java. Dependencies : http://www.mindrot.org/projects/jBCrypt/ OR if you use Maven : <dependency> <groupId>org.mindrot</groupId> <artifactId>jbcrypt</artifactId> <version>0.3m</version> </dependency>
package libs.password;
import java.util.UUID;
/**
* @author vbert
*
*/
public final class HashedPassword{
private String version;
private String passwordHash;
public HashedPassword(String version, String passwordHash) {
super();
this.version = version;
this.passwordHash = passwordHash;
}
public String getVersion() {
return version;
}
public String getPasswordHash() {
return passwordHash;
}
public String toString(){
return version+"#"+passwordHash;
}
public static HashedPassword readFromString(String serialized){
String[] e = serialized.split("#");
return new HashedPassword(e[0], e[1]);
}
}
/**
*
*/
package libs.password.hash;
import java.security.InvalidKeyException;
import java.security.NoSuchAlgorithmException;
import java.util.Properties;
import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import org.apache.commons.codec.binary.Hex;
import org.mindrot.jbcrypt.BCrypt;
import libs.password.HashedPassword;
/**
* @author vbert
*
*/
public class HmacBCryptHash implements PasswordHasher{
private final String HASHER_NAME = "HMAC_BCRYPT";
private Mac mac;
public HmacBCryptHash(Properties prop) throws NoSuchAlgorithmException, InvalidKeyException{
byte[] key = prop.getProperty("password.hmacbcript.key").getBytes();
SecretKeySpec keySpec = new SecretKeySpec(key,"HmacSHA1");
mac = Mac.getInstance("HmacSHA1");
mac.init(keySpec);
}
private String hmac(String str) {
byte[] result = mac.doFinal(str.getBytes());
return Hex.encodeHexString(result);
}
/* (non-Javadoc)
* @see libs.password.hash.PasswordHasher#getHasherName()
*/
@Override
public String getHasherName() {
return HASHER_NAME;
}
/* (non-Javadoc)
* @see libs.password.hash.PasswordHasher#hashPassword(java.lang.String)
*/
@Override
public HashedPassword hashPassword(String password) {
String signPwd = hmac(password);
String pwHash = BCrypt.hashpw(signPwd, BCrypt.gensalt());
return new HashedPassword(HASHER_NAME, pwHash);
}
/* (non-Javadoc)
* @see libs.password.hash.PasswordHasher#verfifyPassword(libs.password.HashedPassword, java.lang.String)
*/
@Override
public boolean verfifyPassword(HashedPassword hash, String password) {
String signPwd = hmac(password);
return BCrypt.checkpw(signPwd, hash.getPasswordHash());
}
}
/**
*
*/
package libs.password.hash;
import libs.password.HashedPassword;
/**
* @author vbert
*
*/
public interface PasswordHasher {
public String getHasherName();
public HashedPassword hashPassword(String password);
public boolean verfifyPassword(HashedPassword hash, String password);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.