com.aspose.words

Class DigitalSignatureUtil

  • java.lang.Object
    • com.aspose.words.DigitalSignatureUtil
public abstract class DigitalSignatureUtil 
extends java.lang.Object

Provides methods for signing document.

Since digital signature works with file content rather than Document Object Model these methods are put into a separate class.

Supported formats are LoadFormat.DOC and LoadFormat.DOCX.

Example:

Shows how to load and remove digital signatures from a digitally signed document.
// Load digital signatures via filename string to verify that the document is signed
DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
Assert.assertEquals(digitalSignatures.getCount(), 1);

// Re-save the document to an output filename with all digital signatures removed
DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx", getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");

// Remove all signatures from the document using stream parameters
FileInputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
FileOutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);

// We can also load a document's digital signatures via stream, which we will do to verify that all signatures have been removed
streamIn = new FileInputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
digitalSignatures = DigitalSignatureUtil.loadSignatures(streamIn);

Assert.assertEquals(digitalSignatures.getCount(), 0);

Method Summary
static DigitalSignatureCollectionloadSignatures(java.io.InputStream stream)
Loads digital signatures from document using stream.
static DigitalSignatureCollectionloadSignatures(java.lang.String fileName)
Loads digital signatures from document.
static voidremoveAllSignatures(java.io.InputStream srcStream, java.io.OutputStream dstStream)
Removes all digital signatures from document in source stream and writes unsigned document to destination stream.

Output will be written to the start of stream and stream size will be updated with content length.

static voidremoveAllSignatures(java.lang.String srcFileName, java.lang.String dstFileName)
Removes all digital signatures from source file and writes unsigned file to destination file.
static voidsign(java.io.InputStream srcStream, java.io.OutputStream dstStream, CertificateHolder certHolder)
Signs source document using given CertificateHolder with digital signature and writes signed document to destination stream.

Document should be either LoadFormat.DOC or LoadFormat.DOCX.

Output will be written to the start of stream and stream size will be updated with content length.

static voidsign(java.io.InputStream srcStream, java.io.OutputStream dstStream, CertificateHolder certHolder, SignOptions signOptions)
Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination stream.

Document should be either LoadFormat.DOC or LoadFormat.DOCX.

Output will be written to the start of stream and stream size will be updated with content length.

static voidsign(java.lang.String srcFileName, java.lang.String dstFileName, CertificateHolder certHolder)
Signs source document using given CertificateHolder with digital signature and writes signed document to destination file.

Document should be either LoadFormat.DOC or LoadFormat.DOCX.

static voidsign(java.lang.String srcFileName, java.lang.String dstFileName, CertificateHolder certHolder, SignOptions signOptions)
Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination file.

Document should be either LoadFormat.DOC or LoadFormat.DOCX.

 

    • Method Detail

      • loadSignatures

        public static DigitalSignatureCollection loadSignatures(java.io.InputStream stream)
                                                             throws java.lang.Exception
        Loads digital signatures from document using stream.
        Parameters:
        stream - Stream with the document.
        Returns:
        Collection of digital signatures. Returns empty collection if file is not signed.

        Example:

        Shows how to load and remove digital signatures from a digitally signed document.
        // Load digital signatures via filename string to verify that the document is signed
        DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
        Assert.assertEquals(digitalSignatures.getCount(), 1);
        
        // Re-save the document to an output filename with all digital signatures removed
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx", getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // Remove all signatures from the document using stream parameters
        FileInputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        FileOutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
        
        // We can also load a document's digital signatures via stream, which we will do to verify that all signatures have been removed
        streamIn = new FileInputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        digitalSignatures = DigitalSignatureUtil.loadSignatures(streamIn);
        
        Assert.assertEquals(digitalSignatures.getCount(), 0);
      • loadSignatures

        public static DigitalSignatureCollection loadSignatures(java.lang.String fileName)
                                                             throws java.lang.Exception
        Loads digital signatures from document.
        Parameters:
        fileName - Path to the document.
        Returns:
        Collection of digital signatures. Returns empty collection if file is not signed.

        Example:

        Shows how to load and remove digital signatures from a digitally signed document.
        // Load digital signatures via filename string to verify that the document is signed
        DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
        Assert.assertEquals(digitalSignatures.getCount(), 1);
        
        // Re-save the document to an output filename with all digital signatures removed
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx", getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // Remove all signatures from the document using stream parameters
        FileInputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        FileOutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
        
        // We can also load a document's digital signatures via stream, which we will do to verify that all signatures have been removed
        streamIn = new FileInputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        digitalSignatures = DigitalSignatureUtil.loadSignatures(streamIn);
        
        Assert.assertEquals(digitalSignatures.getCount(), 0);
      • removeAllSignatures

        public static void removeAllSignatures(java.io.InputStream srcStream, java.io.OutputStream dstStream)
                                            throws java.lang.Exception
        Removes all digital signatures from document in source stream and writes unsigned document to destination stream.

        Output will be written to the start of stream and stream size will be updated with content length.

        Example:

        Shows how to load and remove digital signatures from a digitally signed document.
        // Load digital signatures via filename string to verify that the document is signed
        DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
        Assert.assertEquals(digitalSignatures.getCount(), 1);
        
        // Re-save the document to an output filename with all digital signatures removed
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx", getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // Remove all signatures from the document using stream parameters
        FileInputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        FileOutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
        
        // We can also load a document's digital signatures via stream, which we will do to verify that all signatures have been removed
        streamIn = new FileInputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        digitalSignatures = DigitalSignatureUtil.loadSignatures(streamIn);
        
        Assert.assertEquals(digitalSignatures.getCount(), 0);
      • removeAllSignatures

        public static void removeAllSignatures(java.lang.String srcFileName, java.lang.String dstFileName)
                                            throws java.lang.Exception
        Removes all digital signatures from source file and writes unsigned file to destination file.

        Example:

        Shows how to load and remove digital signatures from a digitally signed document.
        // Load digital signatures via filename string to verify that the document is signed
        DigitalSignatureCollection digitalSignatures = DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
        Assert.assertEquals(digitalSignatures.getCount(), 1);
        
        // Re-save the document to an output filename with all digital signatures removed
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx", getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // Remove all signatures from the document using stream parameters
        FileInputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        FileOutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
        
        // We can also load a document's digital signatures via stream, which we will do to verify that all signatures have been removed
        streamIn = new FileInputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
        digitalSignatures = DigitalSignatureUtil.loadSignatures(streamIn);
        
        Assert.assertEquals(digitalSignatures.getCount(), 0);
      • sign

        public static void sign(java.io.InputStream srcStream, java.io.OutputStream dstStream, CertificateHolder certHolder)
                             throws java.lang.Exception
        Signs source document using given CertificateHolder with digital signature and writes signed document to destination stream.

        Document should be either LoadFormat.DOC or LoadFormat.DOCX.

        Output will be written to the start of stream and stream size will be updated with content length.

        Parameters:
        srcStream - The stream which contains the document to sign.
        dstStream - The stream that signed document will be written to.
        certHolder - CertificateHolder object with certificate that used to sign file.

        Example:

        Shows how to sign documents with X.509 certificates.
        // Verify that a document isn't signed
        Assert.assertFalse(FileFormatUtil.detectFileFormat(getMyDir() + "Document.docx").hasDigitalSignature());
        
        // Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
        CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw", null);
        
        // There are 2 ways of saving a signed copy of a document to the local file system
        // 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
        SignOptions signOptions = new SignOptions();
        signOptions.setSignTime(new Date());
        
        DigitalSignatureUtil.sign(getMyDir() + "Document.docx", getArtifactsDir() + "Document.DigitalSignature.docx",
                certificateHolder, signOptions);
        
        // 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
        InputStream inDoc = new FileInputStream(getMyDir() + "Document.docx");
        try {
            OutputStream outDoc = new FileOutputStream(getArtifactsDir() + "Document.DigitalSignature.docx");
            try {
                DigitalSignatureUtil.sign(inDoc, outDoc, certificateHolder);
            } finally {
                if (outDoc != null) outDoc.close();
            }
        } finally {
            if (inDoc != null) inDoc.close();
        }
        
        Assert.assertTrue(FileFormatUtil.detectFileFormat(getArtifactsDir() + "Document.DigitalSignature.docx").hasDigitalSignature());
        
        // Open the signed document and get its digital signature collection
        Document signedDoc = new Document(getArtifactsDir() + "Document.DigitalSignature.docx");
        DigitalSignatureCollection digitalSignatureCollection = signedDoc.getDigitalSignatures();
        
        // Verify that all of the document's digital signatures are valid and check their details
        Assert.assertTrue(digitalSignatureCollection.isValid());
        Assert.assertEquals(1, digitalSignatureCollection.getCount());
        Assert.assertEquals(DigitalSignatureType.XML_DSIG, digitalSignatureCollection.get(0).getSignatureType());
        Assert.assertEquals("CN=Morzal.Me", signedDoc.getDigitalSignatures().get(0).getIssuerName());
        Assert.assertEquals("CN=Morzal.Me", signedDoc.getDigitalSignatures().get(0).getSubjectName());
      • sign

        public static void sign(java.io.InputStream srcStream, java.io.OutputStream dstStream, CertificateHolder certHolder, SignOptions signOptions)
                             throws java.lang.Exception
        Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination stream.

        Document should be either LoadFormat.DOC or LoadFormat.DOCX.

        Output will be written to the start of stream and stream size will be updated with content length.

        Parameters:
        srcStream - The stream which contains the document to sign.
        dstStream - The stream that signed document will be written to.
        certHolder - CertificateHolder object with certificate that used to sign file.
        signOptions - SignOptions object with various signing options.

        Example:

        Shows how to sign encrypted document opened from a stream.
        FileInputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        FileOutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.SignDocument.docx");
        
        // Create certificate holder from a file
        CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw");
        
        SignOptions signOptions = new SignOptions();
        signOptions.setComments("Encrypted");
        signOptions.setSignTime(new Date());
        signOptions.setDecryptionPassword("docPassword");
        
        // Digitally sign encrypted with "docPassword" document in the specified path
        DigitalSignatureUtil.sign(streamIn, streamOut, certificateHolder, signOptions);
      • sign

        public static void sign(java.lang.String srcFileName, java.lang.String dstFileName, CertificateHolder certHolder)
                             throws java.lang.Exception
        Signs source document using given CertificateHolder with digital signature and writes signed document to destination file.

        Document should be either LoadFormat.DOC or LoadFormat.DOCX.

        Parameters:
        srcFileName - The file name of the document to sign.
        dstFileName - The file name of the signed document output.
        certHolder - CertificateHolder object with certificate that used to sign file.

        Example:

        Shows how to sign documents with X.509 certificates.
        // Verify that a document isn't signed
        Assert.assertFalse(FileFormatUtil.detectFileFormat(getMyDir() + "Document.docx").hasDigitalSignature());
        
        // Create a CertificateHolder object from a PKCS #12 file, which we will use to sign the document
        CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw", null);
        
        // There are 2 ways of saving a signed copy of a document to the local file system
        // 1: Designate unsigned input and signed output files by filename and sign with the passed CertificateHolder
        SignOptions signOptions = new SignOptions();
        signOptions.setSignTime(new Date());
        
        DigitalSignatureUtil.sign(getMyDir() + "Document.docx", getArtifactsDir() + "Document.DigitalSignature.docx",
                certificateHolder, signOptions);
        
        // 2: Create a stream for the input file and one for the output and create a file, signed with the CertificateHolder, at the file system location determine
        InputStream inDoc = new FileInputStream(getMyDir() + "Document.docx");
        try {
            OutputStream outDoc = new FileOutputStream(getArtifactsDir() + "Document.DigitalSignature.docx");
            try {
                DigitalSignatureUtil.sign(inDoc, outDoc, certificateHolder);
            } finally {
                if (outDoc != null) outDoc.close();
            }
        } finally {
            if (inDoc != null) inDoc.close();
        }
        
        Assert.assertTrue(FileFormatUtil.detectFileFormat(getArtifactsDir() + "Document.DigitalSignature.docx").hasDigitalSignature());
        
        // Open the signed document and get its digital signature collection
        Document signedDoc = new Document(getArtifactsDir() + "Document.DigitalSignature.docx");
        DigitalSignatureCollection digitalSignatureCollection = signedDoc.getDigitalSignatures();
        
        // Verify that all of the document's digital signatures are valid and check their details
        Assert.assertTrue(digitalSignatureCollection.isValid());
        Assert.assertEquals(1, digitalSignatureCollection.getCount());
        Assert.assertEquals(DigitalSignatureType.XML_DSIG, digitalSignatureCollection.get(0).getSignatureType());
        Assert.assertEquals("CN=Morzal.Me", signedDoc.getDigitalSignatures().get(0).getIssuerName());
        Assert.assertEquals("CN=Morzal.Me", signedDoc.getDigitalSignatures().get(0).getSubjectName());
      • sign

        public static void sign(java.lang.String srcFileName, java.lang.String dstFileName, CertificateHolder certHolder, SignOptions signOptions)
                             throws java.lang.Exception
        Signs source document using given CertificateHolder and SignOptions with digital signature and writes signed document to destination file.

        Document should be either LoadFormat.DOC or LoadFormat.DOCX.

        Parameters:
        srcFileName - The file name of the document to sign.
        dstFileName - The file name of the signed document output.
        certHolder - CertificateHolder object with certificate that used to sign file.
        signOptions - SignOptions object with various signing options.

        Example:

        Demonstrates how to add new signature line to the document and sign it with personal signature using SignatureLineId.
        public static void sign() throws Exception {
            String signPersonName = "Ron Williams";
            String srcDocumentPath = getMyDir() + "Document.docx";
            String dstDocumentPath = getArtifactsDir() + "SignDocumentCustom.Sign.docx";
            String certificatePath = getMyDir() + "morzal.pfx";
            String certificatePassword = "aw";
        
            // We need to create simple list with test signers for this example
            createSignPersonData();
            System.out.println("Test data successfully added!");
        
            // Get sign person object by name of the person who must sign a document
            // This an example, in real use case you would return an object from a database
            SignPersonTestClass signPersonInfo = gSignPersonList.stream().filter(x -> x.getName() == signPersonName).findFirst().get();
        
            if (signPersonInfo != null) {
                signDocument(srcDocumentPath, dstDocumentPath, signPersonInfo, certificatePath, certificatePassword);
                System.out.println("Document successfully signed!");
            } else {
                System.out.println("Sign person does not exist, please check your parameters.");
            }
        
            // Now do something with a signed document, for example, save it to your database
            // Use 'new Document(dstDocumentPath)' for loading a signed document
        }
        
        /// <summary>
        /// Signs the document obtained at the source location and saves it to the specified destination.
        /// </summary>
        private static void signDocument(final String srcDocumentPath, final String dstDocumentPath,
                                         final SignPersonTestClass signPersonInfo, final String certificatePath,
                                         final String certificatePassword) throws Exception {
            // Create new document instance based on a test file that we need to sign
            Document document = new Document(srcDocumentPath);
            DocumentBuilder builder = new DocumentBuilder(document);
        
            // Add info about responsible person who sign a document
            SignatureLineOptions signatureLineOptions = new SignatureLineOptions();
            signatureLineOptions.setSigner(signPersonInfo.getName());
            signatureLineOptions.setSignerTitle(signPersonInfo.getPosition());
        
            // Add signature line for responsible person who sign a document
            SignatureLine signatureLine = builder.insertSignatureLine(signatureLineOptions).getSignatureLine();
            signatureLine.setId(signPersonInfo.getPersonId());
        
            // Save a document with line signatures into temporary file for future signing
            builder.getDocument().save(dstDocumentPath);
        
            // Create holder of certificate instance based on your personal certificate
            // This is the test certificate generated for this example
            CertificateHolder certificateHolder = CertificateHolder.create(certificatePath, certificatePassword);
        
            // Link our signature line with personal signature
            SignOptions signOptions = new SignOptions();
            signOptions.setSignatureLineId(signPersonInfo.getPersonId());
            signOptions.setSignatureLineImage(signPersonInfo.getImage());
        
            // Sign a document which contains signature line with personal certificate
            DigitalSignatureUtil.sign(dstDocumentPath, dstDocumentPath, certificateHolder, signOptions);
        }
        
        /// <summary>
        /// Create test data that contains info about sing persons.
        /// </summary>
        private static void createSignPersonData() throws IOException {
            InputStream inputStream = new FileInputStream(getImageDir() + "Logo.jpg");
        
            gSignPersonList = new ArrayList<>();
            gSignPersonList.add(new SignPersonTestClass(UUID.randomUUID(), "Ron Williams", "Chief Executive Officer",
                    DocumentHelper.getBytesFromStream(inputStream)));
            gSignPersonList.add(new SignPersonTestClass(UUID.randomUUID(), "Stephen Morse", "Head of Compliance",
                    DocumentHelper.getBytesFromStream(inputStream)));
        }
        
        private static ArrayList<SignPersonTestClass> gSignPersonList;

        Example:

        Shows how to sign documents using certificate holder and sign options.
        CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw");
        
        // By string:
        Document doc = new Document(getMyDir() + "Digitally signed.docx");
        String outputFileName = getArtifactsDir() + "DigitalSignatureUtil.SignDocument.docx";
        
        SignOptions signOptions = new SignOptions();
        signOptions.setComments("Encrypted");
        signOptions.setSignTime(new Date());
        
        DigitalSignatureUtil.sign(doc.getOriginalFileName(), outputFileName, certificateHolder, signOptions);