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

用PDFBox和Bouncycastle签名无效

宫亦
2023-03-14

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创建了证书和密钥对,我现在不知道是问题还是我做错了什么?

暂时还没有答案

 类似资料:
  • 我试图找到用pdfbox版本2签署pdf的例子。x、 在bouncycastle中,我看到的只是pdfbox版本1.8.9 https://github.com/mkl-public/testarea-pdfbox1/blob/master/src/main/java/mkl/testarea/pdfbox1/sign/CreateSignature.java 这适用于pdfbox 1.8.9,但

  • 我在PDF文档中(以编程方式)填写一个表单(AcroPdf),然后在文档上签名。我从doc.pdf开始,使用pdfbox的setfields.java示例创建doc_filler.pdf。然后我对doc_fill.pdf进行签名,创建doc?filled_signer.pdf,使用一些代码,基于签名示例并在Acrobat Reader中打开pdf。输入的字段数据是可见的,并且签名面板告诉我 “此签

  • PDF创建步骤: 通过添加空签名字段名称创建pdf:suhasb@gmail.com和nikhil.courser@gmail.com,使用原始的hello.pdf输出文件名hello_tag.pdf运行程序>tagpdfsignaturefields.java 从hello_tag.pdf文件中提取签名字段suhasb@gmail.com进行首次签名,输出文件名为hello_signd.pdf

  • 我应该如何更改A方法?任何想法都是好的。提前谢谢。

  • 问题内容: 我正在使用和 (Bouncycastle库) 签署,然后验证。 这是我签署的: 现在,输出将在这一过程中使用的: 一切正常,直到由于以下原因: 有人可以给我提示可能发生的事情吗? PS 。如果有人要进行上述测试,则将需要我用来复制此文件的测试文件,只需从这里开始即可: https://www.dropbox.com/s/zs4jo1a86v8qamw/certificates.p12?

  • 我正在使用和(Bouncycastle库)对进行签名,然后验证。 由于以下,: 谁能给我一个可能会发生什么事的提示吗? ps.如果有人想要测试上面的您将需要我正在使用的测试文件来复制该文件,只需从此处即可: https://www.dropbox.com/s/zs4jo1a86v8qamw/certifications.p12?dl=0