/*
 * 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.cryptolib.primitives.ffc;

import java.math.BigInteger;

import com.scytl.cryptolib.primitives.messagedigest.factory.CryptoMessageDigest;

/**
 * Implementation of {@link PseudoRandom}.
 */
class PseudoRandomImpl implements PseudoRandom {
    private final CryptoMessageDigest digest;

    private final int outlen;

    private BigInteger seed;

    /**
     * Constructor.
     * 
     * @param digest
     * @param seed
     */
    public PseudoRandomImpl(CryptoMessageDigest digest, BigInteger seed) {
        this.digest = digest;
        this.outlen = digest.getDigestLength() * Byte.SIZE;
        this.seed = seed;
    }

    @Override
    public BigInteger next() {
        byte[] bytes = digest.generate(seed.toByteArray());
        seed = seed.add(BigInteger.ONE);
        return new BigInteger(1, bytes);
    }

    @Override
    public BigInteger next(int length) {
        int iterations = (length + outlen - 1) / outlen;
        BigInteger value = BigInteger.ZERO;
        for (int i = 0; i < iterations; i++) {
            value = value.add(next().shiftLeft(i * outlen));
        }
        return value;
    }

    @Override
    public BigInteger seed() {
        return seed;
    }
}
