Example usage for com.itextpdf.text.pdf.security PdfPKCS7 getEncodedPKCS7

List of usage examples for com.itextpdf.text.pdf.security PdfPKCS7 getEncodedPKCS7

Introduction

In this page you can find the example usage for com.itextpdf.text.pdf.security PdfPKCS7 getEncodedPKCS7.

Prototype

public byte[] getEncodedPKCS7(byte secondDigest[], TSAClient tsaClient, byte[] ocsp,
        Collection<byte[]> crlBytes, CryptoStandard sigtype) 

Source Link

Document

Gets the bytes for the PKCS7SignedData object.

Usage

From source file:org.opencps.pki.Pkcs7GenerateSignatureContainer.java

License:Open Source License

/**
 * Produces the container with the signature.
 * @param data the data to sign/*from www .  j  ava2 s. c  om*/
 * @return a container with the signature and other objects, like CRL and OCSP. The container will generally be a PKCS7 one.
 * @throws GeneralSecurityException 
 */
@Override
public byte[] sign(InputStream is) throws GeneralSecurityException {
    X509Certificate cert = signer.getCertificate();
    RSAPublicKey rsaKey = (RSAPublicKey) cert.getPublicKey();
    Integer keyLength = rsaKey.getModulus().bitLength() / 8;

    if (keyLength != signature.length) {
        throw new SignatureException("Signature length not correct");
    }

    ExternalDigest digest = signer.getExternalDigest();

    byte[] digestHash = null;
    try {
        digestHash = DigestAlgorithms.digest(is, digest.getMessageDigest(signer.getHashAlgorithm().toString()));
    } catch (IOException e) {
        throw new SignatureException(e.getMessage(), e);
    }

    PdfPKCS7 sgn = new PdfPKCS7(null, new Certificate[] { cert }, signer.getHashAlgorithm().toString(), null,
            digest, false);
    byte[] sh = sgn.getAuthenticatedAttributeBytes(digestHash, null, null, CryptoStandard.CMS);
    Signature sig = Signature
            .getInstance(signer.getHashAlgorithm().toString() + "with" + cert.getPublicKey().getAlgorithm());
    sig.initVerify(cert.getPublicKey());
    sig.update(sh);
    if (!sig.verify(signature)) {
        throw new SignatureException("Signature is not correct");
    }

    TSAClient tsaClient = null;
    String tsaUrl = CertificateUtil.getTSAURL(cert);
    if (tsaUrl != null) {
        tsaClient = new TSAClientBouncyCastle(tsaUrl);
    }

    sgn.setExternalDigest(signature, null, cert.getPublicKey().getAlgorithm());
    return sgn.getEncodedPKCS7(digestHash, tsaClient, null, null, CryptoStandard.CMS);
}