package org.bouncycastle.openpgp.examples;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.security.NoSuchAlgorithmException;
import java.security.NoSuchProviderException;
import java.security.Security;
import java.security.SignatureException;

import org.bouncycastle.bcpg.ArmoredInputStream;
import org.bouncycastle.bcpg.ArmoredOutputStream;
import org.bouncycastle.bcpg.BCPGInputStream;
import org.bouncycastle.bcpg.BCPGOutputStream;
import org.bouncycastle.bcpg.HashAlgorithmTags;
import org.bouncycastle.bcpg.PublicKeyAlgorithmTags;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.openpgp.PGPException;
import org.bouncycastle.openpgp.PGPLiteralData;
import org.bouncycastle.openpgp.PGPCompressedDataGenerator;
import org.bouncycastle.openpgp.PGPCompressedData;
import org.bouncycastle.openpgp.PGPLiteralDataGenerator;
import org.bouncycastle.openpgp.PGPObjectFactory;
import org.bouncycastle.openpgp.PGPOnePassSignature;
import org.bouncycastle.openpgp.PGPOnePassSignatureList;
import org.bouncycastle.openpgp.PGPPrivateKey;
import org.bouncycastle.openpgp.PGPPublicKey;
import org.bouncycastle.openpgp.PGPPublicKeyRing;
import org.bouncycastle.openpgp.PGPSecretKeyRing;
import org.bouncycastle.openpgp.PGPSignature;
import org.bouncycastle.openpgp.PGPSignatureGenerator;
import org.bouncycastle.openpgp.PGPSignatureList;

/**
 * A simple utility class that encrypts/decrypts password based
 * encryption files.
 * <p>
 * To encrypt a file: PBEFileProcessor -e [-a] fileName passPhrase.<br>
 * If -a is specified the output file will be "ascii-armored".
 * <p>
 * To decrypt: PBEFileProcessor -d fileName passPhrase.
 * <p>
 * Note: this example will silently overwrite files, nor does it pay any attention to
 * the specification of "_CONSOLE" in the filename. It also expects that a single pass phrase
 * will have been used.
 */
public class SignedFileProcessor
{
	/**
	 * decrypt the passed in message stream
	 */
	private static void verifyFile(
		InputStream		in,
		InputStream		keyIn,
		boolean			armored)
		throws Exception
	{
		if (armored)
		{
			in = new ArmoredInputStream(in);
		}
		
		PGPObjectFactory				pgpFact = new PGPObjectFactory(in);

		PGPCompressedData 			c1 = (PGPCompressedData)pgpFact.nextObject();

		pgpFact = new PGPObjectFactory(c1.getDataStream());
			
		PGPOnePassSignatureList  	p1 = (PGPOnePassSignatureList)pgpFact.nextObject();
            
		PGPOnePassSignature			ops = p1.get(0);
            
		PGPLiteralData				   	p2 = (PGPLiteralData)pgpFact.nextObject();

		InputStream             			dIn = p2.getInputStream();
		int                     				ch;
		PGPPublicKeyRing				pgpRing = new PGPPublicKeyRing(new BCPGInputStream(keyIn));

		PGPPublicKey						key = pgpRing.getPublicKey();
		FileOutputStream				out = new FileOutputStream(p2.getFileName());

		ops.initVerify(key, "BC");
			
		while ((ch = dIn.read()) >= 0)
		{
			ops.update((byte)ch);
			out.write(ch);
		}

		out.close();
		
		PGPSignatureList         			p3 = (PGPSignatureList)pgpFact.nextObject();

		if (ops.verify(p3.get(0)))
		{
			System.out.println("signature verified.");
		}
		else
		{
			System.out.println("signature verification failed.");
		}
	}

	private static void signFile(
		String				fileName,
		InputStream		keyIn,
		OutputStream	out,
		char[]				pass,
		boolean			armor)
		throws IOException, NoSuchAlgorithmException, NoSuchProviderException, PGPException, SignatureException
	{	
		if (armor)
		{
			out = new ArmoredOutputStream(out);
		}
		
		PGPSecretKeyRing			pgpPriv = new PGPSecretKeyRing(new BCPGInputStream(keyIn));
		PGPPrivateKey				pgpPrivKey = pgpPriv.getSecretKey().extractPrivateKey(pass, "BC");		
		PGPSignatureGenerator	sGen = new PGPSignatureGenerator(PublicKeyAlgorithmTags.RSA_GENERAL, HashAlgorithmTags.SHA1, "BC");
		
		sGen.initSign(PGPSignature.BINARY_DOCUMENT, pgpPrivKey);
		
		PGPCompressedDataGenerator cGen = new PGPCompressedDataGenerator(
																PGPCompressedDataGenerator.ZIP);
		
		BCPGOutputStream			bOut = new BCPGOutputStream(cGen.open(out));
		
		sGen.generateOnePassVersion(false).encode(bOut);
		
		File								file = new File(fileName);
		PGPLiteralDataGenerator	lGen = new PGPLiteralDataGenerator();
		OutputStream				lOut = lGen.open(bOut, PGPLiteralData.BINARY, file);
		FileInputStream				fIn = new FileInputStream(file);
		int								ch = 0;
		
		while ((ch = fIn.read()) >= 0)
		{
			lOut.write(ch);
			sGen.update((byte)ch);
		}
		
		sGen.generate().encode(bOut);
		
		lGen.close();
		
		cGen.close();
		
		out.close();
    }

    public static void main(
    	String[] args)
    	throws Exception
    {
        Security.addProvider(new BouncyCastleProvider());

		if (args[0].equals("-s"))
		{
			if (args[1].equals("-a"))
			{
				FileInputStream		keyIn = new FileInputStream(args[3]);
				FileOutputStream	out = new FileOutputStream(args[2] + ".asc");
				
				signFile(args[2], keyIn, out, args[4].toCharArray(), true);
			}
			else
			{
				FileInputStream		keyIn = new FileInputStream(args[2]);
				FileOutputStream	out = new FileOutputStream(args[1] + ".bpg");
				
				signFile(args[1], keyIn, out, args[3].toCharArray(), false);
			}
		}
		else if (args[0].equals("-v"))
		{
			if (args[1].equals("-a"))
			{
				FileInputStream	in = new FileInputStream(args[2]);
				FileInputStream	keyIn = new FileInputStream(args[3]);
				
				verifyFile(in, keyIn, true);
			}
			else
			{
				FileInputStream	in = new FileInputStream(args[1]);
				FileInputStream	keyIn = new FileInputStream(args[2]);
				
				verifyFile(in, keyIn, false);
			}
		}
		else
		{
			System.err.println("usage: SignedFileProcessor -v|-s [-a] file keyfile");
		}
    }
}
