package cn.report.pdf.sign.base;

import com.itextpdf.kernel.pdf.PdfDocument;
import com.itextpdf.kernel.pdf.PdfReader;
import com.itextpdf.signatures.PdfPKCS7;
import com.itextpdf.signatures.SignatureUtil;
import org.bouncycastle.jce.provider.BouncyCastleProvider;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.Security;
import java.util.List;

public class SignatureIntegrity  
{
	public PdfPKCS7 verifySignature(SignatureUtil signUtil, String name) throws GeneralSecurityException, IOException {
		System.out.println("Signature covers whole document: " + signUtil.signatureCoversWholeDocument(name));
		System.out.println("Document revision: " + signUtil.getRevision(name) + " of " + signUtil.getTotalRevisions());
		PdfPKCS7 pkcs7 = signUtil.readSignatureData(name);
		System.out.println("Integrity check OK? " + pkcs7.verifySignatureIntegrityAndAuthenticity());
		return pkcs7;
	}

	public void verifySignatures(String path) throws IOException, GeneralSecurityException
	{
		PdfDocument pdfDoc = new PdfDocument(new PdfReader(path));
		SignatureUtil signUtil = new SignatureUtil(pdfDoc);
		List<String> names = signUtil.getSignatureNames();
		for (String name : names) {
			System.out.println("签字名：" + name);
			verifySignature(signUtil, name);
		}
		System.out.println();
	}

	public static void main(String[] args) throws IOException, GeneralSecurityException {
		String EXAMPLE1 = "D:/test/pdfs/hello_level_1_annotated.pdf";
		String EXAMPLE2 = "D:/test/pdfs/step_4_signed_by_alice_bob_carol_and_dave.pdf";
		String EXAMPLE3 = "D:/test/pdfs/step_6_signed_by_dave_broken_by_chuck.pdf";

		BouncyCastleProvider provider = new BouncyCastleProvider();
		Security.addProvider(provider);
		SignatureIntegrity app = new SignatureIntegrity();
		app.verifySignatures(EXAMPLE1);
		app.verifySignatures(EXAMPLE2);
		app.verifySignatures(EXAMPLE3);
	}


}
