Setting Argon2 algorithm type in Java

1.1k Views Asked by At

Argon2 by default uses Argon2id. How can I programatically set a different algorthm type in Java? I mean, how to mention my program should use Argon2i or Argon2d in Java?

I wanted to encode a password. I am using Spring Security jar. Used the below code to create the encoder

Argon2PasswordEncoder encoder = new Argon2PasswordEncoder(DEFAULT_SALT_LENGTH, DEFAULT_HASH_LENGTH, DEFAULT_PARALLELISM, 512, 1000);

This is using argon2id by default. Wanted to know how to set a different algorithm.

2

There are 2 best solutions below

0
Mirianna On

You can use Password4j:

int memory = 2048;
int iterations = 10;
int parallelism = 1;
int outputLength = 128;
Argon2 variant = Argon2.D;

Argon2Function argon2 = Argon2Function.getInstance(memory, iterations, parallelism, outputLength, variant);

Hash hash = Password.hash(pwd).addRandomSalt().with(argon2);

You can store the configuration in a properties file as well, so you can just write

Hash hash = Password.hash(pwd).addRandomSalt().withArgon2();

You can find more information in the official documentation.

0
aimass On

You seem to be using an opinionated implementation by Spring Security Argon2PasswordEncoder which defaults to Argon2id. AFAICT it's based on Bouncy Castle so if you want more control then use Bouncy Castle itself: Here are some examples https://www.baeldung.com/java-argon2-hashing