/*
 * This file is part of l2jserver2 <l2jserver2.com>.
 *
 * l2jserver2 is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, either version 3 of the License, or
 * (at your option) any later version.
 *
 * l2jserver2 is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with l2jserver2.  If not, see <http://www.gnu.org/licenses/>.
 */
package com.l2jserver.service.network.keygen;

import java.util.Random;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.l2jserver.service.AbstractService;
import com.l2jserver.service.ServiceStartException;
import com.l2jserver.service.ServiceStopException;

/**
 * Generates a new random key using JDK {@link Random}. Keys generated by this
 * implementation are not completely secure but are very fast to generate.
 * 
 * @author <a href="http://www.rogiel.com">Rogiel</a>
 */
public class PseudoRandomBlowfishKeygenService extends AbstractService
		implements BlowfishKeygenService {
	/**
	 * The logger
	 */
	private final Logger log = LoggerFactory.getLogger(this.getClass());

	/**
	 * The random number generator
	 */
	private Random random;

	@Override
	protected void doStart() throws ServiceStartException {
		random = new Random();
	}

	@Override
	public byte[] generate() {
		log.debug("Generating a new key");

		final byte[] key = new byte[16];
		// randomize the 8 first bytes
		for (int i = 0; i < key.length; i++) {
			key[i] = (byte) random.nextInt(255);
		}

		// the last 8 bytes are static
		key[8] = (byte) 0xc8;
		key[9] = (byte) 0x27;
		key[10] = (byte) 0x93;
		key[11] = (byte) 0x01;
		key[12] = (byte) 0xa1;
		key[13] = (byte) 0x6c;
		key[14] = (byte) 0x31;
		key[15] = (byte) 0x97;
		return key;
	}

	@Override
	protected void doStop() throws ServiceStopException {
		random = null;
	}
}
