0

我正在尝试编写一个服务来处理用户密码哈希和验证。我正在使用 Wildfly Elytron 库并在 quarkus Web 服务的上下文中使用该服务。我遇到的问题是,当我尝试验证密码时,验证方法会抛出java.security.InvalidKeyException, 并显示一条null消息。我一直在使用库的单元测试(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);
        }
    }
4

1 回答 1

0

弄清楚了。我为单元测试发布的原始链接已过时,因此略有错误。

实际(最新)测试

我缺少一个用于解码编码哈希的包装器:

original = (BCryptPassword) passwordFactory.translate(ModularCrypt.decode(encodedPass));

于 2020-02-05T03:03:50.090 回答