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 signatures from a digitally signed document.
// There are two ways of loading a signed document's collection of digital signatures using the DigitalSignatureUtil class.
// 1 -  Load from a document from a local file system filename:
DigitalSignatureCollection digitalSignatures = 
    DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");

// If this collection is nonempty, then we can verify that the document is digitally signed.
Assert.assertEquals(1, digitalSignatures.getCount());

// 2 -  Load from a document from a FileStream.
InputStream stream = new FileInputStream(getMyDir() + "Digitally signed.docx");
try
{
    digitalSignatures = DigitalSignatureUtil.loadSignatures(stream);
    Assert.assertEquals(1, digitalSignatures.getCount());
}
finally { if (stream != null) stream.close(); }

Example:

Shows how to remove digital signatures from a digitally signed document.
// There are two ways of using the DigitalSignatureUtil class to remove digital signatures
// from a signed document by saving an unsigned copy of it somewhere else in the local file system.
// 1 - Determine the locations of both the signed document and the unsigned copy by filename strings:
DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx",
    getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");

// 2 - Determine the locations of both the signed document and the unsigned copy by file streams:
InputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
try
{
    OutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
    try
    {
        DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
    }
    finally { if (streamOut != null) streamOut.close(); }
}
finally { if (streamIn != null) streamIn.close(); }

// Verify that both our output documents have no digital signatures.
Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx").getCount(), 0);
Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx").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 signatures from a digitally signed document.
        // There are two ways of loading a signed document's collection of digital signatures using the DigitalSignatureUtil class.
        // 1 -  Load from a document from a local file system filename:
        DigitalSignatureCollection digitalSignatures = 
            DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
        
        // If this collection is nonempty, then we can verify that the document is digitally signed.
        Assert.assertEquals(1, digitalSignatures.getCount());
        
        // 2 -  Load from a document from a FileStream.
        InputStream stream = new FileInputStream(getMyDir() + "Digitally signed.docx");
        try
        {
            digitalSignatures = DigitalSignatureUtil.loadSignatures(stream);
            Assert.assertEquals(1, digitalSignatures.getCount());
        }
        finally { if (stream != null) stream.close(); }
      • 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 remove digital signatures from a digitally signed document.
        // There are two ways of using the DigitalSignatureUtil class to remove digital signatures
        // from a signed document by saving an unsigned copy of it somewhere else in the local file system.
        // 1 - Determine the locations of both the signed document and the unsigned copy by filename strings:
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx",
            getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // 2 - Determine the locations of both the signed document and the unsigned copy by file streams:
        InputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        try
        {
            OutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
            try
            {
                DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
            }
            finally { if (streamOut != null) streamOut.close(); }
        }
        finally { if (streamIn != null) streamIn.close(); }
        
        // Verify that both our output documents have no digital signatures.
        Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx").getCount(), 0);
        Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx").getCount(), 0);

        Example:

        Shows how to load signatures from a digitally signed document.
        // There are two ways of loading a signed document's collection of digital signatures using the DigitalSignatureUtil class.
        // 1 -  Load from a document from a local file system filename:
        DigitalSignatureCollection digitalSignatures = 
            DigitalSignatureUtil.loadSignatures(getMyDir() + "Digitally signed.docx");
        
        // If this collection is nonempty, then we can verify that the document is digitally signed.
        Assert.assertEquals(1, digitalSignatures.getCount());
        
        // 2 -  Load from a document from a FileStream.
        InputStream stream = new FileInputStream(getMyDir() + "Digitally signed.docx");
        try
        {
            digitalSignatures = DigitalSignatureUtil.loadSignatures(stream);
            Assert.assertEquals(1, digitalSignatures.getCount());
        }
        finally { if (stream != null) stream.close(); }
      • 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 remove digital signatures from a digitally signed document.
        // There are two ways of using the DigitalSignatureUtil class to remove digital signatures
        // from a signed document by saving an unsigned copy of it somewhere else in the local file system.
        // 1 - Determine the locations of both the signed document and the unsigned copy by filename strings:
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx",
            getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // 2 - Determine the locations of both the signed document and the unsigned copy by file streams:
        InputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        try
        {
            OutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
            try
            {
                DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
            }
            finally { if (streamOut != null) streamOut.close(); }
        }
        finally { if (streamIn != null) streamIn.close(); }
        
        // Verify that both our output documents have no digital signatures.
        Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx").getCount(), 0);
        Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx").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 remove digital signatures from a digitally signed document.
        // There are two ways of using the DigitalSignatureUtil class to remove digital signatures
        // from a signed document by saving an unsigned copy of it somewhere else in the local file system.
        // 1 - Determine the locations of both the signed document and the unsigned copy by filename strings:
        DigitalSignatureUtil.removeAllSignatures(getMyDir() + "Digitally signed.docx",
            getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx");
        
        // 2 - Determine the locations of both the signed document and the unsigned copy by file streams:
        InputStream streamIn = new FileInputStream(getMyDir() + "Digitally signed.docx");
        try
        {
            OutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx");
            try
            {
                DigitalSignatureUtil.removeAllSignatures(streamIn, streamOut);
            }
            finally { if (streamOut != null) streamOut.close(); }
        }
        finally { if (streamIn != null) streamIn.close(); }
        
        // Verify that both our output documents have no digital signatures.
        Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromString.docx").getCount(), 0);
        Assert.assertEquals(DigitalSignatureUtil.loadSignatures(getArtifactsDir() + "DigitalSignatureUtil.LoadAndRemove.FromStream.docx").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 is not signed.
        Assert.assertFalse(FileFormatUtil.detectFileFormat(getMyDir() + "Document.docx").hasDigitalSignature());
        
        // Create a CertificateHolder object from a PKCS12 file, which we will use to sign the document.
        CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw", null);
        
        SignOptions signOptions = new SignOptions();
        signOptions.setSignTime(new Date());
        
        // There are two ways of saving a signed copy of a document to the local file system:
        // 1 - Designate a document by a local system filename, and save a signed copy at a location specified by another filename.
        DigitalSignatureUtil.sign(getMyDir() + "Document.docx", getArtifactsDir() + "Document.DigitalSignature.docx", 
            certificateHolder, signOptions);
        
        Assert.assertTrue(FileFormatUtil.detectFileFormat(getArtifactsDir() + "Document.DigitalSignature.docx").hasDigitalSignature());
        
        // 2 - Take a document from a stream, and save a signed copy to another stream.
        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());
        
        // Please verify that all of the document's digital signatures are valid, and check their details.
        Document signedDoc = new Document(getArtifactsDir() + "Document.DigitalSignature.docx");
        DigitalSignatureCollection digitalSignatureCollection = signedDoc.getDigitalSignatures();
        
        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 digitally sign documents.
        // Create an X.509 certificate from a PKCS#12 store, which should contain a private key.
            CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw");
        
            // Create a comment and date which will be applied with our new digital signature.
            SignOptions signOptions = new SignOptions();
            {
                signOptions.setComments("My comment"); 
                signOptions.setSignTime(new Date());
            }
        
            // Take an unsigned document from the local file system via a file stream,
            // then create a signed copy of it determined by the filename of the output file stream.
            InputStream streamIn = new FileInputStream(getMyDir() + "Document.docx");
            try
            {
                OutputStream streamOut = new FileOutputStream(getArtifactsDir() + "DigitalSignatureUtil.SignDocument.docx");
                try
                {
                    DigitalSignatureUtil.sign(streamIn, streamOut, certificateHolder, signOptions);
        }
                finally { if (streamOut != null) streamOut.close(); }
        }
            finally { if (streamIn != null) streamIn.close(); }
      • 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 is not signed.
        Assert.assertFalse(FileFormatUtil.detectFileFormat(getMyDir() + "Document.docx").hasDigitalSignature());
        
        // Create a CertificateHolder object from a PKCS12 file, which we will use to sign the document.
        CertificateHolder certificateHolder = CertificateHolder.create(getMyDir() + "morzal.pfx", "aw", null);
        
        SignOptions signOptions = new SignOptions();
        signOptions.setSignTime(new Date());
        
        // There are two ways of saving a signed copy of a document to the local file system:
        // 1 - Designate a document by a local system filename, and save a signed copy at a location specified by another filename.
        DigitalSignatureUtil.sign(getMyDir() + "Document.docx", getArtifactsDir() + "Document.DigitalSignature.docx", 
            certificateHolder, signOptions);
        
        Assert.assertTrue(FileFormatUtil.detectFileFormat(getArtifactsDir() + "Document.DigitalSignature.docx").hasDigitalSignature());
        
        // 2 - Take a document from a stream, and save a signed copy to another stream.
        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());
        
        // Please verify that all of the document's digital signatures are valid, and check their details.
        Document signedDoc = new Document(getArtifactsDir() + "Document.DigitalSignature.docx");
        DigitalSignatureCollection digitalSignatureCollection = signedDoc.getDigitalSignatures();
        
        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;