使用iText 5对签名的文档进行数字签名

问题描述

您好,我可以使用iText 5对PDF document进行数字签名。我需要再次签名PDF,而在验证PDF时,它表明初始签名无效。您可以查看the file here再次签名。

请参见下面用于sigining的代码

import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.security.GeneralSecurityException;
import java.security.KeyStore;
import java.security.KeyStoreException;
import java.security.NoSuchAlgorithmException;
import java.security.PrivateKey;
import java.security.SignatureException;
import java.security.UnrecoverableKeyException;
import java.security.cert.Certificate;

import com.itextpdf.text.DocumentException;
import com.itextpdf.text.Rectangle;
import com.itextpdf.text.pdf.PdfReader;
import com.itextpdf.text.pdf.PdfSignatureAppearance;
import com.itextpdf.text.pdf.pdfstamper;
import com.itextpdf.text.pdf.security.BouncyCastleDigest;
import com.itextpdf.text.pdf.security.ExternalDigest;
import com.itextpdf.text.pdf.security.ExternalSignature;
import com.itextpdf.text.pdf.security.MakeSignature;
import com.itextpdf.text.pdf.security.PrivateKeySignature;

public class Test {

    

    public static void main(String[] args) throws DocumentException,IOException,GeneralSecurityException {

        PdfReader reader = null;
        PrivateKey pk = null; 
        String alias = "PRASANTH KARUNAKaraN NAIR"; 

        KeyStore ks = null; 
        try { 
            ks = KeyStore.getInstance("Windows-MY","SunMSCAPI"); 
        } 
        catch (KeyStoreException|java.security.NoSuchProviderException e4){ 
            e4.printstacktrace(); 
        }  
        try { 
            ks.load(null,null); 
        } 
        catch (NoSuchAlgorithmException|java.security.cert.CertificateException|IOException e4){ 
            e4.printstacktrace(); 
        } 

        try { 
            pk = (PrivateKey)ks.getKey(alias,"abcd".tochararray()); 
        } 

        catch (UnrecoverableKeyException|KeyStoreException|NoSuchAlgorithmException e3){ 
            e3.printstacktrace(); 
        }  
        Certificate[] chain = null; 
        try { 
            chain = ks.getCertificateChain(alias); 
        } 
        catch (KeyStoreException e3){ 
            e3.printstacktrace(); 
        }  

        
        try {
            reader = new PdfReader("D:///signedSample.pdf"); 
        } 
        catch (IOException e5){ 
            e5.printstacktrace(); 
        }  
        String signedFileNameWithPath = "D:///signedsignedSample.pdf"; 
        FileOutputStream os = null; 
        try { 
            os = new FileOutputStream(signedFileNameWithPath); 
        } 
        catch (FileNotFoundException e5){ 
            e5.printstacktrace();
        }
        pdfstamper stamper = null; 
        
        
        try {
            stamper = pdfstamper.createSignature(reader,os,'\0');
        } 
        catch (DocumentException|IOException e5) {
            e5.printstacktrace(); 
        } 
        
        
        PdfSignatureAppearance appearance = stamper.getSignatureAppearance();
        Integer pageNumber = 2; 
        Rectangle rect=new Rectangle(50,100,220,140);
        appearance.setAcro6Layers(false);
        appearance.setLayer4Text(PdfSignatureAppearance.questionMark);
        appearance.setVisibleSignature(rect,pageNumber,"sig2");

        PrivateKeySignature privateKeySignature=null;
        try {
            privateKeySignature= new PrivateKeySignature(pk,"SHA-256",ks.getProvider().getName()); 
        }
        catch (NullPointerException e) {
        }
        if(privateKeySignature!=null) {
            BouncyCastleDigest bouncyCastleDigest = new BouncyCastleDigest(); 
            try { 
                MakeSignature.signDetached(appearance,(ExternalDigest)bouncyCastleDigest,(ExternalSignature)privateKeySignature,chain,null,MakeSignature.CryptoStandard.CMS);
            } 
            catch (IOException e1){
                e1.printstacktrace(); 
            }
            catch (DocumentException e1){
                e1.printstacktrace(); 
            } 
            catch (SignatureException e1) {
                e1.printstacktrace(); 
            } 
            catch (GeneralSecurityException e1){ 
                e1.printstacktrace(); 
            }  
        }
        
    }

}

请让我知道出了什么问题。

解决方法

如果要将其他签名添加到已签名的PDF中,显然必须小心并且不要更改任何签名的字节。换句话说,添加和更改必须作为增量更新附加到现有文件中。

例如,带有三个签名的PDF的示意图必须与此相似:

(有关背景,请阅读this answer及其引用的文档。)

但是,默认情况下,iText PdfStamper不使用增量更新,而是使用原始文件中的各个对象(可能会完全更改的顺序)创建一个全新的文件,并删除新文件中不需要的对象版本了。当然,这会使第一个签名无效。

要创建使用增量更新工作的PdfStamper,必须使用不同的PdfStamper.createSignature重载。请更换

stamper = PdfStamper.createSignature(reader,os,'\0');

作者

stamper = PdfStamper.createSignature(reader,'\0',null,true);

额外的参数在JavaDocs方法中记录如下:

/* @param reader the original document
 * @param os the output stream or <CODE>null</CODE> to keep the document in the temporary file
 * @param pdfVersion the new pdf version or '\0' to keep the same version as the original
 * document
 * @param tempFile location of the temporary file. If it's a directory a temporary file will be created there.
 *     If it's a file it will be used directly. The file will be deleted on exit unless <CODE>os</CODE> is null.
 *     In that case the document can be retrieved directly from the temporary file. If it's <CODE>null</CODE>
 *     no temporary file will be created and memory will be used
 * @param append if <CODE>true</CODE> the signature and all the other content will be added as a
 * new revision thus not invalidating existing signatures