// SPDX-FileCopyrightText: 2014-2023 Anne Jan Brouwer <brouwer@annejan.com>
// SPDX-FileCopyrightText: 2017 Jason A. Donenfeld <Jason@zx2c4.com>
// SPDX-FileCopyrightText: 2020 Charlie Waters <cawiii@me.com>
// SPDX-FileCopyrightText: 2023 g10 Code GmbH
// SPDX-FileContributor: Sune Stolborg Vuorela <sune@vuorela.dk>
// SPDX-License-Identifier: GPL-3.0-or-later

#include "passwordgenerator.h"

#include <QRandomGenerator>

static quint32 boundedRandom(quint32 bound)
{
    if (bound < 2) {
        return 0;
    }

    quint32 randval;
    const quint32 max_mod_bound = (1 + ~bound) % bound;

    do {
        randval = QRandomGenerator::system()->generate();
    } while (randval < max_mod_bound);

    return randval % bound;
}

QString PasswordGenerator::generateRandomPassword(const QString &charset, unsigned int length)
{
    QString out;
    for (unsigned int i = 0; i < length; ++i) {
        out.append(charset.at(static_cast<int>(boundedRandom(static_cast<quint32>(charset.length())))));
    }
    return out;
}
