Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
package pro.gravit.launchserver.auth.password;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.bouncycastle.crypto.digests.SHA256Digest;
import org.bouncycastle.crypto.generators.PKCS5S2ParametersGenerator;
import org.bouncycastle.crypto.params.KeyParameter;

import java.nio.charset.StandardCharsets;
import java.util.Base64;

public class DjangoPasswordVerifier extends PasswordVerifier {
public final Integer DEFAULT_ITERATIONS = 10000;
private static final Logger logger = LogManager.getLogger();
private static final String algorithm = "pbkdf2_sha256";

public String getEncodedHash(String password, String salt, int iterations) {
PKCS5S2ParametersGenerator generator = new PKCS5S2ParametersGenerator(new SHA256Digest());
Copy link
Contributor

@gravit0 gravit0 Sep 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Если это возможно нужно добавить возможность указания конкретного типа хеша (sha256)

Copy link
Author

@metallnt metallnt Sep 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

pbkdf2 - идет по умолчанию в джанго. Могу указать в readme к примеру. Или добавить в файл, где описание настроек было. Либо, как запросите, так и напишу. он отличается от просто sha256

generator.init(password.getBytes(StandardCharsets.UTF_8), salt.getBytes(), iterations);
byte[] dk = ((KeyParameter) generator.generateDerivedParameters(256)).getKey();
byte[] hashBase64 = Base64.getEncoder().encode(dk);
return new String(hashBase64);
}

public String encode(String password, String salt, int iterations) {
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Стоит добавить переопределение метода encrypt для использования этого метода в FileAuthSystem

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Не уверен, что правильно понял

String hash = getEncodedHash(password, salt, iterations);
return String.format("%s$%d$%s$%s", algorithm, iterations, salt, hash);
Copy link
Contributor

@gravit0 gravit0 Sep 21, 2022

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Эта строка специфична для Django или является общей для всех подобных CMS?
Если специфична то этот код нужно вынести в модуль AddionalHash
Если нет то нужно поменять название класса на более общее

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это специфично только для этого способа кодировки. В этом я уверен только потому, что другие способы не пробовал. Могу проработать полную поддержку всех способов, которые работают на джанго, но это отвлечет меня от основных дел. Предлагаю ввести этот способ, но по любым запросам по джанго, буду править код и вносить изменения. Так же, через пул. Единственный нюанс, что не могу быть всегда онлайн, т.к. работа предполагает долгое отсутствие в зоне действия сети и, тем более, компьютера

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Это специфично только для этого способа кодировки

Переименуйте тогда класс и метод на более общее название этого способа. ( pbkdf2 )

}

@Override
public boolean check(String encryptedPassword, String password) {
String[] params = encryptedPassword.split("\\$");
if (params.length != 4) {
logger.warn(" end 1 " + params.length);
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Поправьте сообщение об ошибке

Copy link
Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Упс. Недосмотр. Для себя делал

return false;
}
int iterations = Integer.parseInt(params[1]);
String salt = params[2];
String hash = encode(password, salt, iterations);
return hash.equals(encryptedPassword);
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ public static void registerProviders() {
providers.register("bcrypt", BCryptPasswordVerifier.class);
providers.register("accept", AcceptPasswordVerifier.class);
providers.register("reject", RejectPasswordVerifier.class);
providers.register("django", DjangoPasswordVerifier.class);
registeredProviders = true;
}
}
Expand Down