Java PDFBox和Bouncycastle的签名无效

Java PDFBox和Bouncycastle的签名无效,java,pdfbox,bouncycastle,Java,Pdfbox,Bouncycastle,我正在尝试签署一份pdf文件,我的代码签署了pdf文件,但当我在Adobe中打开文档时,我得到了这样的回答:我不知道会发生什么 证书生成器 public static BigInteger generateSerial() { SecureRandom random = new SecureRandom(); return BigInteger.valueOf(Math.abs(random.nextLong())); } public static X

我正在尝试签署一份pdf文件,我的代码签署了pdf文件,但当我在Adobe中打开文档时,我得到了这样的回答:我不知道会发生什么

证书生成器

public static BigInteger generateSerial() {
        SecureRandom random = new SecureRandom();
        return BigInteger.valueOf(Math.abs(random.nextLong()));
    }

public static X509Certificate CeriticateGenerator(PublicKey publicKey, PrivateKey privateKey)  throws OperatorCreationException, CertificateException, CertIOException {
    Date startDate = new Date(System.currentTimeMillis());
    Date expiryDate = new Date(System.currentTimeMillis() + 365 * 24 * 60 * 60 * 1000);

    X500Name issuser=new X500Name("cn=Rubrica");
    X500Name subject=new X500Name("cn=Rubrica");
    X509v3CertificateBuilder certGen = new JcaX509v3CertificateBuilder(issuser,
            generateSerial(),
            startDate,
            expiryDate,
            subject,
            publicKey).addExtension(Extension.subjectKeyIdentifier, false, createSubjectKeyId(publicKey))
            .addExtension(Extension.authorityKeyIdentifier, false, createAuthorityKeyId(publicKey))
            .addExtension(Extension.basicConstraints, true, new BasicConstraints(true));

     ContentSigner sigGen = new JcaContentSignerBuilder("SHA512withRSA").setProvider("BC").build(privateKey);
     return new JcaX509CertificateConverter()
          .setProvider(new BouncyCastleProvider()).getCertificate(certGen.build(sigGen));


}
 private static SubjectKeyIdentifier createSubjectKeyId(final PublicKey publicKey) throws OperatorCreationException {
        final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        final DigestCalculator digCalc =
          new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));

        return new X509ExtensionUtils(digCalc).createSubjectKeyIdentifier(publicKeyInfo);
      }

      /**
       * Creates the hash value of the authority public key.
       *
       * @param publicKey of the authority certificate
       *
       * @return AuthorityKeyIdentifier hash
       *
       * @throws OperatorCreationException
       */
      private static AuthorityKeyIdentifier createAuthorityKeyId(final PublicKey publicKey)
        throws OperatorCreationException
      {
        final SubjectPublicKeyInfo publicKeyInfo = SubjectPublicKeyInfo.getInstance(publicKey.getEncoded());
        final DigestCalculator digCalc =
          new BcDigestCalculatorProvider().get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));

        return new X509ExtensionUtils(digCalc).createAuthorityKeyIdentifier(publicKeyInfo);
      }
这是接口签名

public class PDBOXsignerManager implements SignatureInterface{
    private PrivateKey privateKey;
    private Certificate[] certificateChain;


    PDBOXsignerManager(KeyStore keyStore, String password, String appCertificateAlias)  {

        try {
            this.certificateChain = Optional.ofNullable(keyStore.getCertificateChain(appCertificateAlias))
                    .orElseThrow(() -> (new IOException("Could not find a proper certificate chain")));
            this.privateKey = (PrivateKey) keyStore.getKey(appCertificateAlias, password.toCharArray());

            Certificate certificate = this.certificateChain[0];

            if (certificate instanceof X509Certificate) {
                ((X509Certificate) certificate).checkValidity();
            }
        } catch (KeyStoreException | IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (UnrecoverableKeyException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (NoSuchAlgorithmException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (CertificateExpiredException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (CertificateNotYetValidException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }



    }

    @Override
    public byte[] sign(InputStream content) throws IOException {
        try {
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            X509Certificate cert = (X509Certificate) this.certificateChain[0];
            ContentSigner ECDSASigner = new JcaContentSignerBuilder("SHA512withRSA").build(this.privateKey);
            gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build()).build(ECDSASigner, cert));
            gen.addCertificates(new JcaCertStore(Arrays.asList(this.certificateChain)));
            CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
            CMSSignedData signedData = gen.generate(msg, false);



            return signedData.getEncoded();
        } catch (GeneralSecurityException | CMSException | OperatorCreationException e) {
            //throw new IOException cause a SignatureInterface, but keep the stacktrace
            throw new IOException(e);
        }
    }
}
这是类签名者

public class PDBOXSigner extends PDBOXsignerManager
{
 PDBOXSigner(KeyStore keyStore, String password, String appCertificateAlias) {
    super(keyStore, password, appCertificateAlias);
        }

public void signDetached( PDDocument document, OutputStream output, String name, String reason) {
        PDSignature pdSignature = new PDSignature();
        pdSignature.setFilter(PDSignature.FILTER_ADOBE_PPKLITE);
        pdSignature.setSubFilter(PDSignature.SUBFILTER_ADBE_PKCS7_SHA1);
        pdSignature.setName(name);
        pdSignature.setReason(reason);

        // Se le agrega la fecha de firma necesaria para validar la misma
        pdSignature.setSignDate(Calendar.getInstance());

        // Registro del diccionario de firmas y y la interfaz de firma
        try {
             SignatureOptions signatureOptions = new SignatureOptions();
             // Size can vary, but should be enough for purpose.
             signatureOptions.setPreferredSignatureSize(SignatureOptions.DEFAULT_SIGNATURE_SIZE * 2);
             // register signature dictionary and sign interface
             document.addSignature(pdSignature, this, signatureOptions);

            // write incremental (only for signing purpose)
            document.saveIncremental(output);
            output.flush();
            output.close();

        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }


    }
}
我用java和bouncycastle创建了证书和密钥对,我现在不知道是问题还是我做错了什么



错误在于使用了
子过滤器_ADBE_PKCS7_SHA1
而不是在中使用的
子过滤器_ADBE_PKCS7_
。SUBFILTER_ADBE_PKCS7_SHA1不应用于签名,它在PDF 2.0中已被弃用。

您使用的是什么PDFBox和BC版本?您可以共享源文件和结果文件吗?如果使用现有的证书文件,它是否也会失败?(使用
keytool-genkeypair-storepass 123456-storetype pkcs12-alias test-validity 365-v-keyalg RSA-keystore keystore.p12创建一个)(keytool位于jdk bin目录中)请分享一个由您的代码创建的示例pdf。@tilmahausher此版本org.bouncycastle v1.63和pdfbox 2.0.13为什么您使用SUBFILTER_ADBE_PKCS7_SHA1而不是像示例中那样分离的SUBFILTER_ADBE_PKCS7_?@tilmahausher您是个天才,SUBFILTER_ADBE_PKCS7_SHA1这是个问题,因此,y tryng sing whit ECDSA secp256k1,但adobe还不支持这种类型的算法。这不仅是因为if deprecation,更重要的是因为此处不应使用sha1。请看@Tilman Hausherr是的,这是一个愚蠢的错误,但是是一个很好的学习,谢谢你的帮助。帮助,我刚刚看到手机自动拼写更正对我上面的评论做了什么。。。