我正在尝试编写一项服务来处理用户密码哈希和验证。我正在使用Wildfly Elytron库,并在quarkus Web服务的上下文中使用该服务。我遇到的问题是,当我尝试验证密码时,verify方法将抛出java.security.InvalidKeyException
和null
消息。我一直在使用库的unit tests (javatips.net)作为实现的基础,据我所知,我已经正确实现了某些东西。由于异常实际上没有消息,因此很难知道出了什么问题,并且使用谷歌搜索也不会产生太多的收益。有什么想法吗?
public PasswordService(
PasswordValidator passwordValidator //my own password strength validator
){
this.passwordValidator = passwordValidator;
WildFlyElytronPasswordProvider provider = WildFlyElytronPasswordProvider.getInstance();
try {
this.passwordFactory = PasswordFactory.getInstance(ALGORITHM, provider);
} catch (NoSuchAlgorithmException e) {
LOGGER.error("Somehow got an exception when setting up password factory. Error: ", e);
throw new RuntimeException(e);
}
}
public String createPasswordHash(String password) throws PasswordValidationException {
this.passwordValidator.validateAndSanitize(password);
IteratedSaltedPasswordAlgorithmSpec iteratedAlgorithmSpec = new IteratedSaltedPasswordAlgorithmSpec(ITERATIONS, getSalt());
EncryptablePasswordSpec encryptableSpec = new EncryptablePasswordSpec(password.toCharArray(), iteratedAlgorithmSpec);
try {
BCryptPassword original = (BCryptPassword) passwordFactory.generatePassword(encryptableSpec);
return ModularCrypt.encodeAsString(original);
} catch (InvalidKeySpecException e) {
LOGGER.error("Somehow got an invalid key spec. This should not happen. Error: ", e);
throw new WebServerException(e);
}
}
public boolean passwordMatchesHash(String encodedPass, String pass) throws CorruptedKeyException{
BCryptPassword original = null;
try {
original = (BCryptPassword) ModularCrypt.decode(encodedPass);
} catch (InvalidKeySpecException e) {
LOGGER.error("Somehow got an invalid key spec. This should not happen. Error: ", e);
throw new WebServerException(e);
}
try {
return passwordFactory.verify(original, pass.toCharArray()); // throws the invalid key exception
} catch (InvalidKeyException e) {
LOGGER.error("Somehow got an invalid key. This probably shouldn't happen? Error: ", e);
throw new WebServerException(e);
}
}
想通了。我为单元测试发布的原始链接已过时,因此略有错误。
我缺少用于解码编码的哈希的包装器:
original = (BCryptPassword) passwordFactory.translate(ModularCrypt.decode(encodedPass));