Class PdfSigner


  • public class PdfSigner
    extends java.lang.Object
    Takes care of the cryptographic options and appearances that form a signature.
    • Field Detail

      • ID_ATTR_PDF_MAC_DATA

        private static final java.lang.String ID_ATTR_PDF_MAC_DATA
        See Also:
        Constant Field Values
      • raf

        protected java.io.RandomAccessFile raf
        The file right before the signature is added (can be null).
      • bout

        protected byte[] bout
        The bytes of the file right before the signature is added (if raf is null).
      • range

        protected long[] range
        Array containing the byte positions of the bytes that need to be hashed.
      • document

        protected PdfDocument document
        The PdfDocument.
      • cryptoDictionary

        protected PdfSignature cryptoDictionary
        The crypto dictionary.
      • originalOS

        protected java.io.OutputStream originalOS
        OutputStream for the bytes of the document.
      • temporaryOS

        protected java.io.ByteArrayOutputStream temporaryOS
        Outputstream that temporarily holds the output in memory.
      • tempFile

        protected java.io.File tempFile
        Tempfile to hold the output temporarily.
      • exclusionLocations

        protected java.util.Map<PdfName,​PdfLiteral> exclusionLocations
        Name and content of keys that can only be added in the close() method.
      • preClosed

        protected boolean preClosed
        Indicates if the pdf document has already been pre-closed.
      • closed

        protected boolean closed
        Boolean to check if this PdfSigner instance has been closed already or not.
      • acroForm

        private final PdfAcroForm acroForm
        AcroForm for the PdfDocument.
      • signerName

        private java.lang.String signerName
        The name of the signer extracted from the signing certificate.
      • signerProperties

        private SignerProperties signerProperties
        Properties to be used in signing operations.
    • Constructor Detail

      • PdfSigner

        public PdfSigner​(PdfReader reader,
                         java.io.OutputStream outputStream,
                         StampingProperties properties)
                  throws java.io.IOException
        Creates a PdfSigner instance. Uses a ByteArrayOutputStream instead of a temporary file.
        Parameters:
        reader - PdfReader that reads the PDF file
        outputStream - OutputStream to write the signed PDF file
        properties - StampingProperties for the signing document. Note that encryption will be preserved regardless of what is set in properties.
        Throws:
        java.io.IOException - if some I/O problem occurs
      • PdfSigner

        public PdfSigner​(PdfReader reader,
                         java.io.OutputStream outputStream,
                         java.lang.String path,
                         StampingProperties stampingProperties,
                         SignerProperties signerProperties)
                  throws java.io.IOException
        Creates a PdfSigner instance. Uses a ByteArrayOutputStream instead of a temporary file.
        Parameters:
        reader - PdfReader that reads the PDF file
        outputStream - OutputStream to write the signed PDF file
        path - File to which the output is temporarily written
        stampingProperties - StampingProperties for the signing document. Note that encryption will be preserved regardless of what is set in properties.
        signerProperties - SignerProperties bundled properties to be used in signing operations.
        Throws:
        java.io.IOException - if some I/O problem occurs
      • PdfSigner

        public PdfSigner​(PdfReader reader,
                         java.io.OutputStream outputStream,
                         java.lang.String path,
                         StampingProperties properties)
                  throws java.io.IOException
        Creates a PdfSigner instance. Uses a ByteArrayOutputStream instead of a temporary file.
        Parameters:
        reader - PdfReader that reads the PDF file
        outputStream - OutputStream to write the signed PDF file
        path - File to which the output is temporarily written
        properties - StampingProperties for the signing document. Note that encryption will be preserved regardless of what is set in properties.
        Throws:
        java.io.IOException - if some I/O problem occurs
      • PdfSigner

        PdfSigner​(PdfDocument document,
                  java.io.OutputStream outputStream,
                  java.io.ByteArrayOutputStream temporaryOS,
                  java.io.File tempFile)
    • Method Detail

      • setSignerProperties

        public PdfSigner setSignerProperties​(SignerProperties properties)
        Sets the properties to be used in signing operations.
        Parameters:
        properties - the signer properties
        Returns:
        this instance to support fluent interface
      • getSignerProperties

        public SignerProperties getSignerProperties()
        Gets the properties to be used in signing operations.
        Returns:
        the signer properties
      • getSignatureDictionary

        public PdfSignature getSignatureDictionary()
        Returns the user made signature dictionary. This is the dictionary at the /V key of the signature field.
        Returns:
        the user made signature dictionary
      • getSignatureEvent

        public PdfSigner.ISignatureEvent getSignatureEvent()
        Getter for property signatureEvent.
        Returns:
        value of property signatureEvent
      • setSignatureEvent

        public void setSignatureEvent​(PdfSigner.ISignatureEvent signatureEvent)
        Sets the signature event to allow modification of the signature dictionary.
        Parameters:
        signatureEvent - the signature event
      • getNewSigFieldName

        public java.lang.String getNewSigFieldName()
        Gets a new signature field name that doesn't clash with any existing name.
        Returns:
        A new signature field name.
      • getDocument

        public PdfDocument getDocument()
        Gets the PdfDocument associated with this instance.
        Returns:
        the PdfDocument associated with this instance
      • setDocument

        protected void setDocument​(PdfDocument document)
        Sets the PdfDocument.
        Parameters:
        document - The PdfDocument
      • setOriginalOutputStream

        public void setOriginalOutputStream​(java.io.OutputStream originalOS)
        Setter for the OutputStream.
        Parameters:
        originalOS - OutputStream for the bytes of the document
      • signDetached

        public void signDetached​(IExternalDigest externalDigest,
                                 IExternalSignature externalSignature,
                                 java.security.cert.Certificate[] chain,
                                 java.util.Collection<ICrlClient> crlList,
                                 IOcspClient ocspClient,
                                 ITSAClient tsaClient,
                                 int estimatedSize,
                                 PdfSigner.CryptoStandard sigtype)
                          throws java.io.IOException,
                                 java.security.GeneralSecurityException
        Signs the document using the detached mode, CMS or CAdES equivalent.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignature - the interface providing the actual signing
        chain - the certificate chain
        crlList - the CRL list
        ocspClient - the OCSP client
        tsaClient - the Timestamp client
        externalDigest - an implementation that provides the digest
        estimatedSize - the reserved size for the signature. It will be estimated if 0
        sigtype - Either Signature.CMS or Signature.CADES
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDetached

        public void signDetached​(IExternalSignature externalSignature,
                                 java.security.cert.Certificate[] chain,
                                 java.util.Collection<ICrlClient> crlList,
                                 IOcspClient ocspClient,
                                 ITSAClient tsaClient,
                                 int estimatedSize,
                                 PdfSigner.CryptoStandard sigtype)
                          throws java.io.IOException,
                                 java.security.GeneralSecurityException
        Signs the document using the detached mode, CMS or CAdES equivalent.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignature - the interface providing the actual signing
        chain - the certificate chain
        crlList - the CRL list
        ocspClient - the OCSP client
        tsaClient - the Timestamp client
        estimatedSize - the reserved size for the signature. It will be estimated if 0
        sigtype - Either Signature.CMS or Signature.CADES
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDetached

        public void signDetached​(IExternalDigest externalDigest,
                                 IExternalSignature externalSignature,
                                 java.security.cert.Certificate[] chain,
                                 java.util.Collection<ICrlClient> crlList,
                                 IOcspClient ocspClient,
                                 ITSAClient tsaClient,
                                 int estimatedSize,
                                 PdfSigner.CryptoStandard sigtype,
                                 SignaturePolicyInfo signaturePolicy)
                          throws java.io.IOException,
                                 java.security.GeneralSecurityException
        Signs the document using the detached mode, CMS or CAdES equivalent.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignature - the interface providing the actual signing
        chain - the certificate chain
        crlList - the CRL list
        ocspClient - the OCSP client
        tsaClient - the Timestamp client
        externalDigest - an implementation that provides the digest
        estimatedSize - the reserved size for the signature. It will be estimated if 0
        sigtype - Either Signature.CMS or Signature.CADES
        signaturePolicy - the signature policy (for EPES signatures)
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDetached

        public void signDetached​(IExternalSignature externalSignature,
                                 java.security.cert.Certificate[] chain,
                                 java.util.Collection<ICrlClient> crlList,
                                 IOcspClient ocspClient,
                                 ITSAClient tsaClient,
                                 int estimatedSize,
                                 PdfSigner.CryptoStandard sigtype,
                                 SignaturePolicyInfo signaturePolicy)
                          throws java.io.IOException,
                                 java.security.GeneralSecurityException
        Signs the document using the detached mode, CMS or CAdES equivalent.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignature - the interface providing the actual signing
        chain - the certificate chain
        crlList - the CRL list
        ocspClient - the OCSP client
        tsaClient - the Timestamp client
        estimatedSize - the reserved size for the signature. It will be estimated if 0
        sigtype - Either Signature.CMS or Signature.CADES
        signaturePolicy - the signature policy (for EPES signatures)
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDetached

        public void signDetached​(IExternalSignature externalSignature,
                                 java.security.cert.Certificate[] chain,
                                 java.util.Collection<ICrlClient> crlList,
                                 IOcspClient ocspClient,
                                 ITSAClient tsaClient,
                                 int estimatedSize,
                                 PdfSigner.CryptoStandard sigtype,
                                 ISignaturePolicyIdentifier signaturePolicy)
                          throws java.io.IOException,
                                 java.security.GeneralSecurityException
        Signs the document using the detached mode, CMS or CAdES equivalent.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignature - the interface providing the actual signing
        chain - the certificate chain
        crlList - the CRL list
        ocspClient - the OCSP client
        tsaClient - the Timestamp client
        estimatedSize - the reserved size for the signature. It will be estimated if 0
        sigtype - Either Signature.CMS or Signature.CADES
        signaturePolicy - the signature policy (for EPES signatures)
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDetached

        public void signDetached​(IExternalDigest externalDigest,
                                 IExternalSignature externalSignature,
                                 java.security.cert.Certificate[] chain,
                                 java.util.Collection<ICrlClient> crlList,
                                 IOcspClient ocspClient,
                                 ITSAClient tsaClient,
                                 int estimatedSize,
                                 PdfSigner.CryptoStandard sigtype,
                                 ISignaturePolicyIdentifier signaturePolicy)
                          throws java.io.IOException,
                                 java.security.GeneralSecurityException
        Signs the document using the detached mode, CMS or CAdES equivalent.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignature - the interface providing the actual signing
        chain - the certificate chain
        crlList - the CRL list
        ocspClient - the OCSP client
        tsaClient - the Timestamp client
        externalDigest - an implementation that provides the digest
        estimatedSize - the reserved size for the signature. It will be estimated if 0
        sigtype - Either Signature.CMS or Signature.CADES
        signaturePolicy - the signature policy (for EPES signatures)
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signExternalContainer

        public void signExternalContainer​(IExternalSignatureContainer externalSignatureContainer,
                                          int estimatedSize)
                                   throws java.security.GeneralSecurityException,
                                          java.io.IOException
        Sign the document using an external container, usually a PKCS7. The signature is fully composed externally, iText will just put the container inside the document.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        externalSignatureContainer - the interface providing the actual signing
        estimatedSize - the reserved size for the signature
        Throws:
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
        java.io.IOException - if some I/O problem occurs
      • timestamp

        public void timestamp​(ITSAClient tsa,
                              java.lang.String signatureName)
                       throws java.io.IOException,
                              java.security.GeneralSecurityException
        Signs a document with a PAdES-LTV Timestamp. The document is closed at the end.

        NOTE: This method closes the underlying pdf document. This means, that current instance of PdfSigner cannot be used after this method call.
        Parameters:
        tsa - the timestamp generator
        signatureName - the signature name or null to have a name generated automatically
        Throws:
        java.io.IOException - if some I/O problem occurs or estimation for timestamp signature, provided with ITSAClient.getTokenSizeEstimate(), is not big enough
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDeferred

        @Deprecated
        public static void signDeferred​(PdfDocument document,
                                        java.lang.String fieldName,
                                        java.io.OutputStream outs,
                                        IExternalSignatureContainer externalSignatureContainer)
                                 throws java.io.IOException,
                                        java.security.GeneralSecurityException
        Signs a PDF where space was already reserved.
        Parameters:
        document - the original PDF
        fieldName - the field to sign. It must be the last field
        outs - the output PDF
        externalSignatureContainer - the signature container doing the actual signing. Only the method ExternalSignatureContainer.sign is used
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • signDeferred

        public static void signDeferred​(PdfReader reader,
                                        java.lang.String fieldName,
                                        java.io.OutputStream outs,
                                        IExternalSignatureContainer externalSignatureContainer)
                                 throws java.io.IOException,
                                        java.security.GeneralSecurityException
        Signs a PDF where space was already reserved.
        Parameters:
        reader - PdfReader that reads the PDF file
        fieldName - the field to sign. It must be the last field
        outs - the output PDF
        externalSignatureContainer - the signature container doing the actual signing. Only the method ExternalSignatureContainer.sign is used
        Throws:
        java.io.IOException - if some I/O problem occurs
        java.security.GeneralSecurityException - if some problem during apply security algorithms occurs
      • processCrl

        protected java.util.Collection<byte[]> processCrl​(java.security.cert.Certificate cert,
                                                          java.util.Collection<ICrlClient> crlList)
                                                   throws java.security.cert.CertificateEncodingException
        Processes a CRL list.
        Parameters:
        cert - a Certificate if one of the CrlList implementations needs to retrieve the CRL URL from it.
        crlList - a list of CrlClient implementations
        Returns:
        a collection of CRL bytes that can be embedded in a PDF
        Throws:
        java.security.cert.CertificateEncodingException - if an encoding error occurs in Certificate.
      • isPreClosed

        protected boolean isPreClosed()
        Checks if the document is in the process of closing.
        Returns:
        true if the document is in the process of closing, false otherwise
      • preClose

        protected void preClose​(java.util.Map<PdfName,​java.lang.Integer> exclusionSizes)
                         throws java.io.IOException
        This is the first method to be called when using external signatures. The general sequence is: preClose(), getDocumentBytes() and close().

        exclusionSizes must contain at least the PdfName.CONTENTS key with the size that it will take in the document. Note that due to the hex string coding this size should be byte_size*2+2.

        Parameters:
        exclusionSizes - Map with names and sizes to be excluded in the signature calculation. The key is a PdfName and the value an Integer. At least the /Contents must be present
        Throws:
        java.io.IOException - on error
      • populateExistingSignatureFormField

        protected PdfSigFieldLock populateExistingSignatureFormField​(PdfAcroForm acroForm)
        Populates already existing signature form field in the acroForm object. This method is called during the preClose(Map) method if the signature field already exists.
        Parameters:
        acroForm - PdfAcroForm object in which the signature field will be populated
        Returns:
        signature field lock dictionary
      • createNewSignatureFormField

        protected PdfSigFieldLock createNewSignatureFormField​(PdfAcroForm acroForm,
                                                              java.lang.String name)
        Creates new signature form field and adds it to the acroForm object. This method is called during the preClose(Map) method if the signature field doesn't exist.
        Parameters:
        acroForm - PdfAcroForm object in which new signature field will be added
        name - the name of the field
        Returns:
        signature field lock dictionary
      • getRangeStream

        protected java.io.InputStream getRangeStream()
                                              throws java.io.IOException
        Gets the document bytes that are hashable when using external signatures. The general sequence is: preClose(Map), getRangeStream() and close(PdfDictionary).
        Returns:
        the InputStream of bytes to be signed
        Throws:
        java.io.IOException - if some I/O problem occurs
      • close

        protected void close​(PdfDictionary update)
                      throws java.io.IOException
        This is the last method to be called when using external signatures. The general sequence is: preClose(), getDocumentBytes() and close().

        update is a PdfDictionary that must have exactly the same keys as the ones provided in preClose(Map).

        Parameters:
        update - a PdfDictionary with the key/value that will fill the holes defined in preClose(Map)
        Throws:
        java.io.IOException - on error
      • getUnderlyingSource

        protected IRandomAccessSource getUnderlyingSource()
                                                   throws java.io.IOException
        Returns the underlying source.
        Returns:
        the underlying source
        Throws:
        java.io.IOException - if some I/O problem occurs
      • addDocMDP

        protected void addDocMDP​(PdfSignature crypto)
        Adds keys to the signature dictionary that define the certification level and the permissions. This method is only used for Certifying signatures.
        Parameters:
        crypto - the signature dictionary
      • addFieldMDP

        protected void addFieldMDP​(PdfSignature crypto,
                                   PdfSigFieldLock fieldLock)
        Adds keys to the signature dictionary that define the field permissions. This method is only used for signatures that lock fields.
        Parameters:
        crypto - the signature dictionary
        fieldLock - the PdfSigFieldLock instance specified the field lock to be set
      • documentContainsCertificationOrApprovalSignatures

        protected boolean documentContainsCertificationOrApprovalSignatures()
        Check if current document instance already contains certification or approval signatures.
        Returns:
        true if document contains certification or approval signatures, false otherwise
      • getWidgetRectangle

        protected Rectangle getWidgetRectangle​(PdfWidgetAnnotation widget)
        Get the rectangle associated to the provided widget.
        Parameters:
        widget - PdfWidgetAnnotation to extract the rectangle from
        Returns:
        Rectangle
      • getWidgetPageNumber

        protected int getWidgetPageNumber​(PdfWidgetAnnotation widget)
        Get the page number associated to the provided widget.
        Parameters:
        widget - PdfWidgetAnnotation from which to extract the page number
        Returns:
        page number
      • createSignatureDictionary

        PdfSignature createSignatureDictionary​(boolean includeDate)
      • embedMacTokenIntoSignatureContainer

        byte[] embedMacTokenIntoSignatureContainer​(byte[] signatureContainer)
                                            throws java.io.IOException
        Throws:
        java.io.IOException
      • embedMacTokenIntoSignatureContainer

        static byte[] embedMacTokenIntoSignatureContainer​(byte[] signatureContainer,
                                                          java.io.InputStream rangeStream,
                                                          PdfDocument document)
      • getSignerName

        private static java.lang.String getSignerName​(java.security.cert.X509Certificate certificate)
      • updateFieldName

        private void updateFieldName()
      • isDocumentPdf2

        private boolean isDocumentPdf2()
      • applyDefaultPropertiesForTheNewField

        private void applyDefaultPropertiesForTheNewField​(PdfSignatureFormField sigField)
      • setContent

        private void setContent()
      • populateExistingModelElement

        private void populateExistingModelElement()
      • getFieldName

        private java.lang.String getFieldName()