/*
 * Copyright 2018 Scytl Secure Electronic Voting SA
 *
 * All rights reserved
 *
 * See our extended copyright notice in *file 'Copyright.txt' which is part of this source code package
 */
package com.scytl.products.ov.utils;

import java.security.SecureRandom;

import com.scytl.cryptolib.commons.constants.Constants;
import com.scytl.cryptolib.primitives.securerandom.configuration.SecureRandomPolicyFromProperties;
import com.scytl.cryptolib.primitives.securerandom.factory.SecureRandomFactory;


/**
 * Class that generates secure random strings using a specific alphabet
 */
public class SecureRandomStringGenerator {

    private String _alphabet;

    private SecureRandom _secureRandom;

    public SecureRandomStringGenerator(String alphabet) {
        this._alphabet = alphabet;
        this._secureRandom = new SecureRandomFactory(
            new SecureRandomPolicyFromProperties(Constants.CRYPTOLIB_POLICY_PROPERTIES_FILE_PATH)).createSecureRandom();
    }

    /**
     * Generates the random string
     * 
     * @param stringLength
     *            length in characters of generated random string
     * @return random string
     */
    public String generate(int stringLength) {
        StringBuilder result = new StringBuilder();

        for (int j = 0; j < stringLength; j++) {
            int generatedInteger = _secureRandom.nextInt(_alphabet.length());
            result.append(_alphabet.charAt(generatedInteger));
        }

        return result.toString();
    }

}
