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

Java IText7 PDF签名问题-文档在签名后已被更改或损坏

左丘智渊
2023-03-14

我试图对pdf文件进行签名,但在Adobe中打开签名的pdf文件时,遇到“文档自签名后已被更改或损坏”错误。

这个错误不是那么描述性的,我不确定应该在哪里查看,因为代码对我来说似乎很好,但显然不是。。

我使用的代码是:

public class SafeService_INPUT_Pdf {

    private static final String input = "";
    private static final String tmp = "";
    private static final String output =  "";
    private static final String token = "";

    public static void main(String[] args) throws Exception {

        BouncyCastleProvider providerBC = new BouncyCastleProvider();
        Security.addProvider(providerBC);

        CredentialsInfoResponseDto credentialsInfoResponseDto = SafeAmaHelper.getCredentialsInfo(token);

        String cert0 = "-----BEGIN CERTIFICATE-----\n"+ credentialsInfoResponseDto.getCert().getCertificates().get(0) +"\n-----END CERTIFICATE-----";
        String cert1 = "-----BEGIN CERTIFICATE-----\n"+ credentialsInfoResponseDto.getCert().getCertificates().get(1) +"\n-----END CERTIFICATE-----";
        String cert2 = "-----BEGIN CERTIFICATE-----\n"+ credentialsInfoResponseDto.getCert().getCertificates().get(2) +"\n-----END CERTIFICATE-----";

        Certificate[] chain = new Certificate[3];

        try {
            chain[0] = SafePdfHelper.convertStringCert(cert0);
            chain[1] = SafePdfHelper.convertStringCert(cert1);
            chain[2] = SafePdfHelper.convertStringCert(cert2);
        }catch (Exception e){
            System.out.println(e.getCause().getMessage());
        }

        byte[] hash4Sign = SafePdfHelper.emptySignature(input, tmp, "sig", chain);

        //concatenate sha_prefix with hash4Sign and convert to BASE64
        String **hashToSign** = SafePdfHelper.getHashtoSign(hash4Sign);
        
        //CALL AMA and gets 
        String amaSignature = SafeAmaHelper.getAssinat(token,**hashToSign**).getSignatures().get(0);

        byte[] signedFinallyHash = Base64.getDecoder().decode(String.valueOf(amaSignature.toCharArray()));

        //insert HASH (AMA) to PDF temp and creates a signed PDF
        SafePdfHelper.createSignature(signedFinallyHash, tmp, output, "sig", chain);
    }
public class SafePdfHelper {

    public static String getHashtoSign(byte[] hash4Sign) throws NoSuchAlgorithmException {

        byte[] sha256SigPrefix = { 0x30, 0x31, 0x30, 0x0d, 0x06, 0x09, 0x60, (byte) 0x86, 0x48, 0x01, 0x65, 0x03, 0x04, 0x02, 0x01, 0x05, 0x00, 0x04, 0x20 };

        byte[] hash4SignWithPrefix = new byte[sha256SigPrefix.length + hash4Sign.length];
        System.arraycopy(sha256SigPrefix, 0, hash4SignWithPrefix, 0, sha256SigPrefix.length);
        System.arraycopy(hash4Sign, 0, hash4SignWithPrefix, sha256SigPrefix.length, hash4Sign.length);

        return Base64.getEncoder().encodeToString(hash4SignWithPrefix);
    }

    public static Certificate convertStringCert(String certificate) throws Exception{
        InputStream targetStream = new ByteArrayInputStream(certificate.getBytes());

        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        Certificate cert = cf.generateCertificate(targetStream);

        return cert;
    }

    public static byte[] emptySignature(String src, String dest, String fieldname, Certificate[] chain) throws IOException, GeneralSecurityException, IOException {

        PdfReader reader = new PdfReader(src);
        FileOutputStream os = new FileOutputStream(dest);
        PdfSigner signer = new PdfSigner(reader, os, new StampingProperties().useAppendMode());

        signer.setFieldName(fieldname);

        SafePdfHelper.MyExternalBlankSignatureContainer external = new SafePdfHelper.MyExternalBlankSignatureContainer(chain, PdfName.Adobe_PPKMS, PdfName.Adbe_pkcs7_detached);

        signer.signExternalContainer(external, 12000);
        byte[] hash4Sign = external.getHash4Sign();

        os.close();
        reader.close();

        return hash4Sign;
    }

    static class MyExternalBlankSignatureContainer implements IExternalSignatureContainer {

        /* Signature dictionary. Filter and SubFilter.  */
        private final PdfDictionary sigDic;
        private byte[] hash4Sign = null;
        private Certificate[] chain = null;

        public MyExternalBlankSignatureContainer(Certificate[] _chain, PdfName filter, PdfName subFilter) {
            sigDic = new PdfDictionary();
            sigDic.put(PdfName.Filter, filter);
            sigDic.put(PdfName.SubFilter, subFilter);
            chain = _chain;
        }

        public byte[] getHash4Sign() {
            return hash4Sign;
        }

        @Override
        public byte[] sign(InputStream data) throws GeneralSecurityException {

            try {
                String hashAlgorithm = DigestAlgorithms.SHA256;//"SHA-256";
                BouncyCastleDigest digest = new BouncyCastleDigest();
                MessageDigest md = digest.getMessageDigest(hashAlgorithm);

                byte[] hash = DigestAlgorithms.digest(data, md);
                PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);

                OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle(null);
                Collection<byte[]> ocsp = new ArrayList<>();
                for (var i = 0; i < chain.length - 1; i++) {
                    byte[] encoded = ocspClient.getEncoded((X509Certificate) chain[i], (X509Certificate) chain[i + 1], null);
                    if (encoded != null) ocsp.add(encoded);
                }

                byte[] attributeBytes = sgn.getAuthenticatedAttributeBytes(hash, PdfSigner.CryptoStandard.CMS, ocsp, null);

                //create sha256 message digest
                hash4Sign = MessageDigest.getInstance(hashAlgorithm).digest(attributeBytes);

                return new byte[0];
            } catch (IOException | GeneralSecurityException de) {
                de.printStackTrace();
                throw new GeneralSecurityException(de);
            }
        }

        @Override
        public void modifySigningDictionary(PdfDictionary signDic) {
            signDic.putAll(sigDic);
        }
    }


    public static void createSignature(byte[] hashSigned, String src, String dest, String fieldName, Certificate[] chain) throws IOException, GeneralSecurityException {

        PdfReader reader = new PdfReader(src);
        try (FileOutputStream os = new FileOutputStream(dest)) {
            PdfSigner signer = new PdfSigner(reader, os, new StampingProperties());

            IExternalSignatureContainer external = new SafePdfHelper.MyExternalSignatureContainer(hashSigned, chain, PdfName.Adobe_PPKMS, PdfName.Adbe_pkcs7_detached);

            // Signs a PDF where space was already reserved. The field must cover the whole document.
            signer.signDeferred(signer.getDocument(), fieldName, os, external);
        }
        reader.close();
    }

    static class MyExternalSignatureContainer implements IExternalSignatureContainer {

        /* Signature dictionary. Filter and SubFilter.  */
        private PdfDictionary sigDic;
        private byte[] signedHash = null;
        private Certificate[] chain = null;

        public MyExternalSignatureContainer(byte[] _signedHash, Certificate[] _chain, PdfName filter, PdfName subFilter) {
            sigDic = new PdfDictionary();
            sigDic.put(PdfName.Filter, filter);
            sigDic.put(PdfName.SubFilter, subFilter);
            signedHash = _signedHash;
            chain = _chain;
        }

        @Override
        public byte[] sign(InputStream data) throws GeneralSecurityException {
            try {
                String hashAlgorithm = DigestAlgorithms.SHA256;//"SHA-256";
                BouncyCastleDigest digest = new BouncyCastleDigest();
                MessageDigest md = digest.getMessageDigest(hashAlgorithm);

                byte[] hash = DigestAlgorithms.digest(data, md);
                PdfPKCS7 sgn = new PdfPKCS7(null, chain, hashAlgorithm, null, digest, false);

                OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle(null);
                Collection<byte[]> ocsp = new ArrayList<>();
                for (var i = 0; i < chain.length - 1; i++) {
                    byte[] encoded = ocspClient.getEncoded((X509Certificate) chain[i], (X509Certificate) chain[i + 1], null);
                    if (encoded != null) ocsp.add(encoded);
                }

                sgn.setExternalDigest(signedHash, null, "RSA");

                ITSAClient tsaClient = null;//new GSTSAClient(access);
                return sgn.getEncodedPKCS7(hash, PdfSigner.CryptoStandard.CMS, tsaClient, ocsp, null);
            } catch (IOException | GeneralSecurityException de) {
                de.printStackTrace();
                throw new GeneralSecurityException(de);
            }
        }

        @Override
        public void modifySigningDictionary(PdfDictionary signDic) {
            signDic.putAll(sigDic);
        }
    }

签名的哈希的Base64格式为(tmp文件sha_前缀):

MDEwDQYJYIZIAWUDBAIBBQAEIKCZG8Xc6M2de3fuj8CMHLhW8XvMArW6Smy75TgABlGQ

签名(AMA)的Base64格式为:

X5vg7qXJNsiB8hYtauih/wMFNf9uLAnT8h4M7DvHyw0bLdM03BJc7Ar1yGIoA0MTXaEdq85DP6JJFeMJZBRRc/NTA1C4IpjBN5N5Fpaa7HFnNxORQBc00d/bXuSzV1DNwCdIfcDYSUjh5Z3OWFdWzqmDhmAWRK/Hudf90m34B1mpfTtvtRAzrgn79fIBUd9D09iXpnClqTVYIzWcJ+Dz6yU75a0gvR79wNLCpUYNw2kxdmp/odAMm5cn10x9hLB+UhaNSUsnYyQUZtFsSkIE+oPXFqZc9ky4j5ha9Xfz8GGcLPEkAupyxOb5f9/NGicOeegX793swY09O4NxDW9RVtMtmdKt8kZAxB70PG1r18Ui2gheY4yuMg2aqpkcw5vgBO1GYe2DwDp99Qs4xHJjhbiUZOKT0moU+tDb3EySHZkkkci/GQTUg8IYHU8umv9TyuD7A3NRBQTyQud6j9H6bG3zQE+V4T8N2fnUPmoFEfDWyIvxvV+7YL+BymeZX4A0

有人能帮忙吗?

共有1个答案

松波
2023-03-14

这是我们在评论中讨论的概要。

问题是您在MyExternalBlankSignatureContainer中检索OCSP响应。在MyExternalSignatureContainer中签名。在两种执行方法中签名

java prettyprint-override">OcspClientBouncyCastle ocspClient = new OcspClientBouncyCastle(null);
Collection<byte[]> ocsp = new ArrayList<>();
for (var i = 0; i < chain.length - 1; i++) {
    byte[] encoded = ocspClient.getEncoded((X509Certificate) chain[i], (X509Certificate) chain[i + 1], null);
    if (encoded != null) ocsp.add(encoded);
}

并将该列表与PdfPKCS7一起使用。

当您使用MyExternalBlankSignatureContainer来计算要签名的属性摘要,以及使用MyExternalSignatureContainer来基于该摘要的签名值构建签名容器时,这两种情况下的属性必须相同。由于OCSP响应包含在其中一个属性中,这意味着您必须在这两种情况下使用相同的OCSP响应。

但是OCSP响应通常会为每个请求重新创建(或者最多缓存很短的时间),对于同一证书的不同请求,通常会得到不同的OCSP响应。

因此,您不能在MyExternalSignatureContainer中重新检索它们。签名,但必须重新使用您在MyExternalBlankSignatureContainer中检索到的签名。签名。

根据你最后的评论,这样做对你有用。

 类似资料:
  • 我正在使用PDFbox-1.8.8在PDF文件上做签名功能。 当我签署一份文件的时候 下面是我的代码:

  • 对于一个关于签名数据被哈希两次的C#问题,我看到了一个类似的答复,但是我不知道为什么我的签名数据会出现在这里。 C#PKCS7 Smartchard数字签名损坏

  • 我正在按代码创建一个签名PDF,但由于某种原因,我收到此错误: 至少一个签名无效-文档签名后已被更改或损坏 我将DSS属性与VRI、Certs和CRL一起使用。重要的一点是,我使用的版本与我在讨论此过程的其他文章中看到的版本相同。所以我有第一部分的签名(内容<>和byterange[])和第二部分与他的孩子的DSS。我注意到,如果删除第二个生成的部分,Adobe Acrobat将给出: 已签名且所

  • 我尝试使用智能卡(USB令牌)对pdf文件进行签名,但在Adobe中打开签名的pdf文件时,遇到错误。这个错误不是描述性的,我也不知道该去哪里看,因为代码对我来说似乎很好,但显然不是… 我使用的代码是: 我尝试签名的pdf文件是这个。 添加签名字段后创建的临时pdf文件如下。 签名的Base64格式为

  • 我已经研究了所有类似的问题,但找不到一个应用itextsharp延迟签名的案例。 基本上,我的应用程序使用签名对pdf文档进行签名,该签名是由远程web服务创建的。 我的应用程序向这个web服务发送原始文档的哈希(添加空签名字段后可签名字节的哈希),并接收一个Base64编码的签名文件。 我将此签名嵌入到先前生成的临时pdf文件中,该文件具有空签名字段。 最后,我的签名未被验证,因为Adobe R