Skip to content
Guides

Verify Digital Signatures

Verifying a digital signature consists of signature validity and certificate trustworthiness. Signature validity indicates that the document has not been tampered with. Certificate trustworthiness confirms that the signer is trustworthy.

Generally, a signature is verified only when both the signature is valid and the certificate is trustworthy.

This example shows how to verify digital signatures:

java
CPDFDocument document = new CPDFDocument();
document.open(FileUtils.getAssetsTempFile("Signed.pdf"));
// Iterate through all digital signatures.
for (int i = 0; i < document.getSignatureCount(); i++) {
    CPDFSignature signature = document.getPdfSignature(i);
    // Check if the signer array exists and is not empty.
    if (signature.getSignerArr() != null && signature.getSignerArr().length > 0) {
        CPDFSigner signer = signature.getSignerArr()[0];

        // Verify the validity of the signature.
        boolean verifyValid = signature.verify(document);

        // Verify if the document has not been modified.
        boolean unmodified = signature.verifyDocument(document);

        // Determine if the signature is valid and the document is unmodified.
        boolean isSignVerified = verifyValid && unmodified;

        // Check if the certificate is trusted.
        boolean certChainTrusted = signer.getCert().verifyGetChain(rootDir+"/certificate/", signature);
        boolean certificateIsTrusted = signer.getCert().checkCertificateIsTrusted(rootDir + "/trusted");
        boolean certIsTrusted = certChainTrusted || certificateIsTrusted;

        // Check if the certificate has expired.
        boolean isExpired = signer.getCert().isExpired();
        if (isExpired) {
            System.out.println("the certificate is expired.");
        }else {
            System.out.println("the certificate not expired.");
        }

        // Take appropriate actions based on the verification results.
        if (isSignVerified && certIsTrusted) {
            // Signature is valid and the certificate is trusted.
            // Perform the corresponding actions.
            System.out.println("Signature is valid and the certificate is trusted.");
            System.out.println("Perform the corresponding actions.");
        } else if (isSignVerified && !certIsTrusted) {
            // Signature is valid but the certificate is not trusted.
            // Perform the corresponding actions.
            System.out.println("Signature is valid but the certificate is not trusted.");
            System.out.println("Perform the corresponding actions.");
        } else {
            // Signature is invalid.
            // Perform the corresponding actions.
            System.out.println("Signature is invalid.");
            System.out.println("Perform the corresponding actions.");
        }
    }
}