Marcos
Marcos

Reputation: 5027

Encrypt & Decrypt password using Jasypt

It's for a desktop app, so only I want basic login security and I though to use one function to encrypt password and another which I pass pass password from UI and hash save into db and returns true o false depends on if matches or not.

I try to use pooled version from official jasypt website, and I can encrypt but I don't know how to decrypt it.

//Function to encrypt password
public static String cifrarClave(String clave) {
    PooledStringDigester digester = new PooledStringDigester();
    digester.setPoolSize(4);
    digester.setAlgorithm("SHA-1");
    digester.setIterations(50000);
    digester.setSaltSizeBytes(32);

    //String return is hash that I save into db
    return digester.digest(clave);
}

//Function to decrypt password
//clave is old plain that user enter from UI and I want to compare from hash save it into db
public static boolean validarClave(String clave, String hash) {
    PooledStringDigester digester = new PooledStringDigester();
    digester.setPoolSize(4); 
    digester.setAlgorithm("SHA-1");
    digester.setIterations(50000);

    String digest = digester.digest(clave);

    //Always fails at that point, I get different hash from compare clave
    return digester.matches(digest, hash);
}

I'm a newbie in security, so I don't know much about security, I accept other suggestions or alternatives, I only want a working example.

Upvotes: 2

Views: 4192

Answers (1)

fspinnenhirn
fspinnenhirn

Reputation: 1889

You're using the jasypt's matches(message, digest) function incorrectly when you are calling it with two hash digests instead of the plaintext message and the previously computed digest.

In your validarClave(), you're first unnecessarily computing a digest from the user's plaintext password (clave) which you then pass to the matcher:

String digest = digester.digest(clave);
//Always fails at that point, I get different hash from compare clave
return digester.matches(digest, hash);

Your method will work correctly if you simply pass the plaintext password to the matcher, as follows:

digester.matches(clave, hash);

More info is available at jasypt's javadocs and code examples.

Upvotes: 1

Related Questions