package aalg.crypto;

import java.util.Arrays;

/**
 * Symmetric key stored in byte array.
 * @author Ing. Petr Ležák
 */
public class ByteArraySymmetricKey implements ISymmetricKey {
	
	private final byte[] data;
	
	/**
	 * Creates key with given size.
	 * @param size number of bytes of the key
	 */
	public ByteArraySymmetricKey(final int size) {
		this.data = new byte[size];
	}
	
	public ByteArraySymmetricKey(final byte[] key) {
		this(key, 0, key.length);
	}
	
	public ByteArraySymmetricKey(final byte[] key, final int offset, final int size) {
		this.data = new byte[size];
		System.arraycopy(key, offset, data, 0, size);
	}

	@Override
	public void destroy() {
		Arrays.fill(data, (byte) 0);
	}
	
	@Override
	protected void finalize() {
		destroy();
	}
	
	/**
	 * Returns size of the key.
	 * @return size of the key
	 */
	public int getSize() {
		return data.length;
	}

	@Override
	public ByteArraySymmetricKey getSubKey (final int offset, final int size) {
		return new ByteArraySymmetricKey(data, offset, size);
	}
	
	/**
	 * Returns byte at given index.
	 * @param index index of byte
	 * @return byte
	 */
	public byte getByte (final int index) {
		return data[index];
	}

	/**
	 * Sets byte at given index.
	 * @param index index of byte
	 * @param value new value of byte
	 */
	public void setByte (final int index, final byte value) {
		data[index] = value;
	}

}
