简体   繁体   中英

Use BouncyCastle to generate Signed File

I have a PDF file and I use this code to sign this file:

certificate = (X509Certificate) loadKeyStore(certificateFile, password).getCertificate(alias);
    privateKey = (PrivateKey) loadKeyStore(certificateFile, password).getKey(alias, alias.toCharArray());
    Security.addProvider(new BouncyCastleProvider());
    BufferedInputStream inFile = new BufferedInputStream(new FileInputStream(origem));
    byte[] dates = new byte[inFile.available()];
    entrada.read(dates);
    entrada.close();
    CMSSignedDataGenerator genetateSign = new CMSSignedDataGenerator();
    geradorAss.addSigner(privateKey, certificate, CMSSignedDataGenerator.DIGEST_SHA1);
    List certList = new ArrayList();
    certList.add(certificate);
    CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList));
    geradorAss.addCertificatesAndCRLs(certs);
    // Efetivamente assinar os dados de entrada  
    CMSProcessable content = new CMSProcessableByteArray(dates);
    String providerName;
    if (ks.getType().equalsIgnoreCase("JKS")) {
        providerName = BouncyCastleProvider.PROVIDER_NAME;
    } else {
        providerName = ks.getProvider().getName();
    }
    CMSSignedData signedDate = genetateSign.generate(content, providerName);
    signedDate = new CMSSignedData(content, signedDate.getEncoded());

    File f = Converter.converter("signedFile.pdf", signedDate.getEncoded());

But, the file f no open on reader. When I get the file f and run this code:

CMSSignedData data = new CMSSignedData(new FileInputStream(f));

Occur this error:

org.bouncycastle.cms.CMSException: Malformed content.

Someone can help me?

Summarizing:

I need to generate the final file after signing. For example, I have a test.pdf file, I want to sign and generate test_signed.pdf file. And this test_signed.pdf file must have the signature and should still be readable in your reader.

I'm waiting...

PDF has an embedded signature inside the document, while CMS is signature itself. To extract and verify signature from PDF use iText library. Here is an example .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM