Skip to content

Developer Guide

David Bertoldi edited this page Feb 21, 2021 · 1 revision

Write your HashingFunction

We suggest to simply extend the AbstractHashingFunction and implement its the abstract methods

public class MyFunction extends AbstractHashingFunction
{
    @Override
    public Hash hash(CharSequence plainTextPassword)
    {
        // hash plainTextPassword without salt
        ...
        return new Hash(this, hashAsString, hashAsBytes, null);
    }

    @Override
    public Hash hash(CharSequence plainTextPassword, String salt)
    {
        // hash plainTextPassword with a salt
        ...
        return new Hash(this, hashAsString, hashAsBytes, salt);
    }

    @Override
    public boolean check(CharSequence plainTextPassword, String hashed)
    {
        // verify the plainTextPassword and the hash
        ...
        return true / false;
    }
}

The pepper is already prepended to plainTextPassword, so you don't need to manage it.

If you really need to use the pepper in a different way, implement the HashingFunction interface. In this case remember to set the pepper in the Hash object

public class MyFunction implements HashingFunction
{

    @Override
    public Hash hash(CharSequence plainTextPassword)
    {
        // hash plainTextPassword without salt
        ...
        return new Hash(this, hashAsString, hashAsBytes, null);
    }

    @Override
    public Hash hash(CharSequence plainTextPassword, String salt)
    {
        // hash plainTextPassword with a salt
        ...
        return new Hash(this, hashAsString, hashAsBytes, salt);
    }

    @Override
    public Hash hash(CharSequence plainTextPassword, String salt, CharSequence pepper)
    {
        // hash plainTextPassword with a salt and pepper
        ...
        Hash result = new Hash(this, hashAsString, hashAsBytes, salt);
        hash.setPepper(pepper);
        return result;
    }

    @Override
    public boolean check(CharSequence plainTextPassword, String hashed)
    {
        // verify the plainTextPassword and the hash
        ...
        return true / false;
    }

    @Override
    public boolean check(CharSequence plainTextPassword, String hashed, String salt)
    {
        // verify the plainTextPassword and the hash with salt
        ...
        return true / false;
    }

    @Override
    public boolean check(CharSequence plainTextPassword, String hashed, String salt, CharSequence pepper)
    {
        // verify the plainTextPassword and the hash with salt and pepper
        ...
        return true / false;
    }
}

Once you have created your implementation class you can use it like this

MyFunction myFunction = new MyFunction();

Password.hash(plainTextPassword).addSalt(salt).addPepper(pepper).with(myFunction);

Password4j documentation

Clone this wiki locally