当前位置: 首页 > 知识库问答 >
问题:

使用iText(signdeferred)创建PDF数字签名,验证签名时出现无效签名问题

秋飞鸾
2023-03-14
    null
 /**
 * @return name.ldd.electSign.webservice.pdf.presign.PresignResponseDetail
 * @Author 焦康
 * @Description 预签章
 * @Date 2021/4/25 14:35
 * @Param [pdfReader, tempFile, temp, chain, positions, fieldName, calendar, hashName]
 **/
public PreSignResponseDetail preSign(PreSignDAO preSignDAO) throws IOException, DocumentException, GeneralSecurityException {
    log.debug("执行预签章");
    FileOutputStream fileOutputStream = new FileOutputStream(preSignDAO.getTempPath());
    // 设置印章信息
    preSignDAO.getPdfReader().setAppendable(true);
    PdfStamper pdfStamper = PdfStamper.createSignature(preSignDAO.getPdfReader(), fileOutputStream, '\0', null, true);
    pdfStamper.getWriter().setCompressionLevel(PdfStream.BEST_COMPRESSION);
    PdfSignatureAppearance pdfSignatureAppearance = pdfStamper.getSignatureAppearance();
    pdfSignatureAppearance.setReason("");
    pdfSignatureAppearance.setLocation("");
    pdfSignatureAppearance.setContact("");
    pdfSignatureAppearance.setLayer2Text("");
    pdfSignatureAppearance.setLayer4Text("");
    pdfSignatureAppearance.setSignatureCreator("");
    pdfSignatureAppearance.setOpacity(preSignDAO.getSealOpacity());
    pdfSignatureAppearance.setCertificationLevel(PdfSignatureAppearance.NOT_CERTIFIED);
    pdfSignatureAppearance.setRenderingMode(PdfSignatureAppearance.RenderingMode.DESCRIPTION);
    pdfSignatureAppearance.setCertificate(preSignDAO.getCertificateChain()[0]);
    pdfSignatureAppearance.setVisibleSignature(new Rectangle(200, 200, 300, 300), preSignDAO.getPage(), preSignDAO.getFieldName());
    // 设置签名图片
    //读取图章图片,这个image是itext包的image
    Image image = Image.getInstance(preSignDAO.getSealImagePath());
    pdfSignatureAppearance.setImage(image);
    // 开始预签章
    ExternalSignatureContainer externalBlankSignatureContainer = new ExternalBlankSignatureContainer(PdfName.ADOBE_PPKLITE, PdfName.ADBE_PKCS7_DETACHED);
    MakeSignature.signExternalContainer(pdfSignatureAppearance, externalBlankSignatureContainer, 8192);
    // 计算hash
    InputStream inputStream = pdfSignatureAppearance.getRangeStream();
    BouncyCastleDigest bouncyCastleDigest = new BouncyCastleDigest();
    byte[] hash = DigestAlgorithms.digest(inputStream, bouncyCastleDigest.getMessageDigest(preSignDAO.getHashAlgorithm()));
    PdfPKCS7 pkcs7 = new PdfPKCS7(null, preSignDAO.getCertificateChain(), preSignDAO.getHashAlgorithm(), null, bouncyCastleDigest, false);
    byte[] sh = pkcs7.getAuthenticatedAttributeBytes(hash, Calendar.getInstance(), null, null, MakeSignature.CryptoStandard.CMS);
    String stringSh = new sun.misc.BASE64Encoder().encode(sh);
    return new PreSignResponseDetail(preSignDAO.getSourcePath(), preSignDAO.getTempPath(), hash, stringSh.replace("\r\n",""), preSignDAO.getFieldName());

}
/**
     * @Author 焦康
     * @Description 数据签名
     * @Date 2021/4/30 14:57
     * @Param [Pin, CN, signData, listener]
     * @return void
     **/
    public void ZAYK_SignData(final String Pin,final String CN,final String signData,HttpsCallbackListener listener){
        httpsCallbackListener = listener;
        new Thread(new Runnable() {
            @Override
            public void run() {
                String result = null;
                try {
                    byte[] bytes = Base64.decode(signData,Base64.DEFAULT);
                    result = service.SDZM_SignData(bytes,CN,Pin);
                    JSONObject jsonObject = JSONObject.parseObject(result);
                    result = jsonObject.getString("signValue");
                    Log.e("SDZM_SignData",result);
                } catch (Exception e) {
                    e.printStackTrace();
                }
                sendMessage(result);
            }
        }).start();
    }
/**
     * @return
     * @Author 焦康
     * @Description 延迟签章
     * @Date 2021/4/25 17:01
     * @Param
     **/
    public DeferredSignResponseDetail DeferredSign(DeferredSignDAO deferredSignDAO) {
        log.debug("执行延迟签章");
        BouncyCastleDigest bouncyCastleDigest = new BouncyCastleDigest();
        Calendar calendar = Calendar.getInstance();
        calendar.setTime(new Date());
        PdfReader pdfReader = null;
        FileOutputStream os = null;
        try {
            PdfPKCS7 sgn = new PdfPKCS7(null, deferredSignDAO.getCertificateChain(), deferredSignDAO.getHashAlgorithm(), null, bouncyCastleDigest, false);
            sgn.setExternalDigest(deferredSignDAO.getSignData(), null, deferredSignDAO.getDigestEncryptionAlgorithm());
            byte[] sig = sgn.getEncodedPKCS7(deferredSignDAO.getHashData(), calendar, null, null, null, MakeSignature.CryptoStandard.CMS);
            pdfReader = new PdfReader(deferredSignDAO.getTempPath());
            os = new FileOutputStream("D:\\ruoyi\\uploadPath\\pdf\\Dest\\输出");
            ExternalSignatureContainer external = new MyExternalSignatureContainer(sig);
            MakeSignature.signDeferred(pdfReader, deferredSignDAO.getFieldName(), os, external);
        } catch (Exception e) {
            log.error("延迟签章出错:", e);
        } finally {
            if (pdfReader != null) {
                pdfReader.close();
            }
            try {
                if (os != null) {
                    os.close();
                }
            } catch (Exception ex) {
                ex.printStackTrace();
            }
        }
        return new DeferredSignResponseDetail(deferredSignDAO.getTargetPath() + ".pdf");
    }
public class MyExternalSignatureContainer implements ExternalSignatureContainer {
    byte[] sig = null;
    
    public MyExternalSignatureContainer(byte[] sig) {
        this.sig = sig;
    }

    @Override
    public byte[] sign(InputStream paramInputStream) throws GeneralSecurityException {
        return this.sig;
    }

    @Override
    public void modifySigningDictionary(PdfDictionary paramPdfDictionary) {
    }
}

共有1个答案

孟花蜂
2023-03-14
PdfPKCS7 pkcs7 = new PdfPKCS7(null, preSignDAO.getCertificateChain(), preSignDAO.getHashAlgorithm(), null, bouncyCastleDigest, false);
byte[] sh = pkcs7.getAuthenticatedAttributeBytes(hash, Calendar.getInstance(), null, null, MakeSignature.CryptoStandard.CMS);
String stringSh = new sun.misc.BASE64Encoder().encode(sh);
Calendar calendar = Calendar.getInstance();
calendar.setTime(new Date());
...
PdfPKCS7 sgn = new PdfPKCS7(null, deferredSignDAO.getCertificateChain(), deferredSignDAO.getHashAlgorithm(), null, bouncyCastleDigest, false);
sgn.setExternalDigest(deferredSignDAO.getSignData(), null, deferredSignDAO.getDigestEncryptionAlgorithm());
byte[] sig = sgn.getEncodedPKCS7(deferredSignDAO.getHashData(), calendar, null, null, null, MakeSignature.CryptoStandard.CMS);
 类似资料:
  • 我正在尝试用Itext 5和BouncyCastle 1.48验证PDF签名。我的代码适用于许多已签名的pdf,但也适用于特定客户的某些pdf。这是我的Java代码 有时我会遇到这样的例外: JAVAlang.IllegalArgumentException:getInstance:org中的未知对象。蹦蹦跳跳。asn1。Asn1在组织中列举。蹦蹦跳跳。asn1。ASN1序列。组织上的getIns

  • 我正在尝试从外部远程服务对文档进行签名。签署过程分两个阶段进行。远程服务在第一阶段期待base64编码的散列,并在身份验证后发出令牌。在第二阶段,我们将使用接收到的令牌再次传递相同的散列并获得base64签名的散列。我在这里附上签名错误的文件。文件 如果有人可以分析它并指导我评估无效签名背后的原因。我正在使用执行与pdf相关的操作。 更新 根据反馈,我做了一些更正。文档现在正在更改。已更改的文档

  • 我正在用C#开发一个执行数字签名验证的webserver,以确保pdf文件没有被修改。我使用了iText和iTextSharp。 和我的C#验证码: 在VerifySignature(name)行中;抛出NullReferenceException! 有趣的是,如果我使用C#代码执行签名,我就可以在java中验证它,因为我添加了这些指令:BouncyCastleProvider provider=

  • 我正在尝试用Itext 5.4和BouncyCastle 1.49验证PDF签名(它是通过Adobe Reader X用我的数字证书手动签名的)。 但是验证结果总是出乎意料的,下面是我的Java代码: 控制台显示:完整性检查OK?真

  • 我想使用iText 7对pdf文档进行数字签名。签名由仅返回PKCS1签名的外部服务创建。然后我必须创建和应用PKCS7。 iText中有一个很好的关于此场景的文档:https://kb.itextpdf.com/home/it7kb/examples/how-to-use-a-digital-signing-service-dss-such-as-globalsign-with-itext-7

  • 作为我对客户机/服务器pdf签名研究的一部分,我测试了itext pdf延迟签名示例。不幸的是,我得到的合并空签名pdf和哈希值的pdf ie输出显示无效签名。 下面是我的代码片段 我正在使用pkcss11 usb令牌进行签名