使用BouncyCastle生成签名文件

时间:2013-12-19 15:05:52

标签: java bouncycastle

我有一个PDF文件,我使用此代码对此文件进行签名:

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());

但是,文件f在阅读器上没有打开。当我得到文件f并运行此代码时:

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

发生此错误:

org.bouncycastle.cms.CMSException: Malformed content.

有人可以帮助我吗?

汇总:

我需要在签名后生成最终文件。例如,我有一个test.pdf文件,我想签名并生成test_signed.pdf文件。此test_signed.pdf文件必须具有签名,并且仍应在您的阅读器中可读。

我等了......

1 个答案:

答案 0 :(得分:0)

PDF在文档中包含嵌入式签名,而CMS本身就是签名。要从PDF中提取和验证签名,请使用iText库。这是一个example