Skip to content

验证数字签名

验证数字签名包含两个部分:验证签名有效和验证证书可信。

签名有效代表文档未被篡改,证书可信代表签名者是可信任的。一般来说,签名有效且证书可信才代表一个签名验证通过。

验证数字签名的关键代码如下:

java
CPDFDocument document = new CPDFDocument();
document.open(FileUtils.getAssetsTempFile("Signed.pdf"));
// 获取文档中所有的数字签名。
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.");
        }
    }
}