package aalg.crypto;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import aalg.algebra.IElement;
import aalg.algebra.SubGroupDefinition;
import aalg.algebra.Utils;

public class DlKeyIo<T extends IElement> implements IAssymetricKeyIo<DlPrivateKey, DlPublicKey<T>> {

	private final SubGroupDefinition<T> subGroupDefinition;
	
	public DlKeyIo (final SubGroupDefinition<T> subGroupDefinition) {
		this.subGroupDefinition = subGroupDefinition;
	}
	
	public void writePublicKey (final DlPublicKey<T> key, final OutputStream stream) throws IOException {
		subGroupDefinition.getGroup().writeElement(key.getKey(), stream);
	}
	
	public DlPublicKey<T> readPublicKey (final InputStream stream) throws IOException {
		final T element = subGroupDefinition.getGroup().readElement(stream);
		
		return new DlPublicKey<T>(element);
	}
	
	public void writePrivateKey (final DlPrivateKey key, final OutputStream stream) throws IOException {
		Utils.writeNumber(key.getKey(), stream);
	}
	
	public DlPrivateKey readPrivateKey (final InputStream stream) throws IOException {
		return new DlPrivateKey(Utils.readNumber(stream));
	}

}
