package org.bouncycastle.openpgp;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.interfaces.DSAParams;
import java.security.interfaces.DSAPublicKey;
import java.security.interfaces.RSAPublicKey;
import java.util.Date;

import org.bouncycastle.bcpg.DSAPublicBCPGKey;
import org.bouncycastle.bcpg.ElGamalPublicBCPGKey;
import org.bouncycastle.bcpg.PublicKeyAlgorithmTags;
import org.bouncycastle.bcpg.PublicKeyPacket;
import org.bouncycastle.bcpg.RSAPublicBCPGKey;
import org.bouncycastle.jce.interfaces.ElGamalPublicKey;
import org.bouncycastle.jce.spec.ElGamalParameterSpec;

/**
 * general class to handle a PGP secret key object.
 */
public class PGPKeyPair
	implements PublicKeyAlgorithmTags
{
	private long 		keyID;
	private byte[]	fingerPrint;
	
	PGPPublicKey		pub;
	PrivateKey			privKey;
	
	public PGPKeyPair(
		int					algorithm,
		PublicKey			pubKey,
		PrivateKey			privKey,
		Date					time,
		String				provider)
		throws PGPException, NoSuchProviderException
	{
		PublicKeyPacket			pubPk;
		MessageDigest 			sha;
		
		this.privKey = privKey;
		
		try
		{
			sha = MessageDigest.getInstance("SHA1", provider);
		}
		catch (NoSuchAlgorithmException e)
		{
			throw new PGPException("can't find SHA1 digest");
		}
		
		if (pubKey instanceof RSAPublicKey)
		{
			RSAPublicKey		rK = (RSAPublicKey)pubKey;
			
			pubPk = new PublicKeyPacket(algorithm, time, new RSAPublicBCPGKey(rK.getModulus(), rK.getPublicExponent()));
		}
		else if (pubKey instanceof DSAPublicKey)
		{
			DSAPublicKey	dK = (DSAPublicKey)pubKey;
			DSAParams		dP = dK.getParams();
			
			pubPk = new PublicKeyPacket(algorithm, time, new DSAPublicBCPGKey(dP.getP(), dP.getQ(), dP.getG(),  dK.getY()));
		}
		else if (pubKey instanceof ElGamalPublicKey)
		{
			ElGamalPublicKey			eK = (ElGamalPublicKey)pubKey;
			ElGamalParameterSpec	eS = eK.getParams();
			
			pubPk = new PublicKeyPacket(algorithm, time, new ElGamalPublicBCPGKey(eS.getP(), eS.getG(), eK.getY()));
		}
		else
		{
			throw new PGPException("unknown key class");
		}
	}
	
    public PGPPublicKey getPublicKey()
    {
    	return pub;
    }
    
	public PGPPrivateKey getPrivateKey()
	{
		return new PGPPrivateKey(privKey, pub.getKeyID());
	}
}