Example usage for org.bouncycastle.cms CMSSignedDataStreamGenerator CMSSignedDataStreamGenerator

List of usage examples for org.bouncycastle.cms CMSSignedDataStreamGenerator CMSSignedDataStreamGenerator

Introduction

In this page you can find the example usage for org.bouncycastle.cms CMSSignedDataStreamGenerator CMSSignedDataStreamGenerator.

Prototype

public CMSSignedDataStreamGenerator() 

Source Link

Document

base constructor

Usage

From source file:de.mendelson.util.security.BCCryptoHelper.java

public void signCMS(InputStream unsigned, OutputStream signed, final String ALGORITHM_NAME,
        Certificate signCert, Key signKey, boolean inMemory) throws Exception {
    CMSSignedDataStreamGenerator generator = new CMSSignedDataStreamGenerator();
    PrivateKey signPrivKey = this.getPrivateKey(signKey);
    ContentSigner contentSigner = new JcaContentSignerBuilder(ALGORITHM_NAME).setProvider("BC")
            .build(signPrivKey);//w w w  .  ja  va2s.  com
    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(contentSigner,
                    new X509CertificateHolder(signCert.getEncoded())));
    if (inMemory) {
        ByteArrayOutputStream memBuffer = new ByteArrayOutputStream();
        OutputStream signedOut = generator.open(memBuffer, true);
        this.copyStreams(unsigned, signedOut);
        signedOut.flush();
        signedOut.close();
        signed.write(memBuffer.toByteArray());
    } else {
        File tempFile = File.createTempFile("sign", ".temp");
        FileOutputStream fileBuffer = null;
        OutputStream signedOut = null;
        try {
            fileBuffer = new FileOutputStream(tempFile);
            signedOut = generator.open(fileBuffer, true);
            this.copyStreams(unsigned, signedOut);
        } finally {
            if (signedOut != null) {
                signedOut.flush();
                signedOut.close();
            }
            if (fileBuffer != null) {
                fileBuffer.flush();
                fileBuffer.close();
            }
        }
        FileInputStream fileIn = null;
        try {
            fileIn = new FileInputStream(tempFile);
            this.copyStreams(fileIn, signed);
        } finally {
            if (fileIn != null) {
                fileIn.close();
            }
        }
        boolean deleted = tempFile.delete();
    }
}

From source file:org.cryptoworkshop.ximix.client.verify.test.VerifierTest.java

License:Apache License

private byte[] getSequence(byte[] init, MessageChooser chooser) throws Exception {
    CMSSignedDataParser cmsParser = new CMSSignedDataParser(new BcDigestCalculatorProvider(),
            new ByteArrayInputStream(init));
    ASN1InputStream aIn = new ASN1InputStream(cmsParser.getSignedContent().getContentStream());
    ByteArrayOutputStream bOut = new ByteArrayOutputStream();

    CMSSignedDataStreamGenerator cmsGen = new CMSSignedDataStreamGenerator();

    OutputStream outputStream = cmsGen.open(bOut, true);
    DEROutputStream dOut = new DEROutputStream(outputStream);
    ASN1Primitive obj;//from w w  w  . j  av  a 2s. c  o m

    int count = 0;
    while ((obj = aIn.readObject()) != null) {
        if (chooser.chooseMessage(count++)) {
            dOut.writeObject(obj);
        }
    }

    dOut.close();
    cmsParser.close();
    outputStream.close();

    return bOut.toByteArray();
}

From source file:org.dihedron.crypto.operations.sign.pkcs7.PKCS7Signer.java

License:Open Source License

/**
 * Constructor./*from  ww  w.  j a  v a  2 s.  c om*/
 * 
 * @param alias
 *   the alias of the certificate to be used for signing.
 * @param keyring
 *   the key ring containing the private key used for signing.
 * @param provider
 *   the security provider backing up the key ring functionalities.
 * @param algorithm
 *   the digest and encryption algorithm combination used to create the 
 *   signature.
 * @throws CryptoException
 *   if any among alias, key ring and provider is null. 
 * @throws KeyStoreException 
 * @throws CertificateEncodingException 
 * @throws CertificateNotYetValidException 
 * @throws CertificateExpiredException 
 */
public PKCS7Signer(String alias, KeyRing keyring, Provider provider, SignatureAlgorithm algorithm)
        throws CryptoException, KeyStoreException, CertificateEncodingException,
        CertificateNotYetValidException, CertificateExpiredException {
    super(alias, keyring, provider);
    logger.debug("creating PKCS#7 signer with '{}' signature algorithm", algorithm);
    try {
        logger.info("signing with alias '{}'", alias);

        // retrieve key and certificate
        Key key = keyring.getPrivateKey(alias);
        X509Certificate x509certificate = (X509Certificate) keyring.getCertificate(alias);

        // this may throw a CertificateExpiredException or CertificateNotYetValidException
        x509certificate.checkValidity();
        logger.info("certificate is valid at current date");

        // TODO: check CRL

        logger.info("certificate is active at current date (CRL check successful)");

        // prepare the certificates store
        List<Certificate> certificates = new ArrayList<>();
        certificates.add(x509certificate);
        Store store = new JcaCertStore(certificates);

        logger.info("certificate store is ready");

        ContentSigner signer = new JcaContentSignerBuilder(algorithm.toBouncyCastleCode())
                .setProvider((provider instanceof AutoCloseableProvider)
                        ? ((AutoCloseableProvider) provider).getWrappedProvider()
                        : provider)
                .build((PrivateKey) key);

        DigestCalculatorProvider digest = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();

        SignerInfoGenerator signerinfo = new SignerInfoGeneratorBuilder(digest).setDirectSignature(false) // include signed attributes; if true it signs data only
                .setSignedAttributeGenerator(
                        new PKCS7AttributeTableGenerator(algorithm.getDigestAlgorithm(), x509certificate)) // this generates the attributes that will be signed along with the data
                .build(signer, new JcaX509CertificateHolder(x509certificate)); // and then we build the generator

        logger.info("signer info generator is ready");

        generator = new CMSSignedDataStreamGenerator();
        generator.addSignerInfoGenerator(signerinfo);
        generator.addCertificates(store);
        //generator.addCRLs(crlStore);

        logger.debug("signed data stream generator for PKCS#7 is ready");

    } catch (OperatorCreationException e) {
        logger.error("error creating operator", e);
        throw new CryptoException("error creating signing operator (BouncyCastle)", e);
    } catch (CertificateEncodingException e) {
        logger.error("invalid certificate encoding", e);
        throw e;
    } catch (CertificateExpiredException e) {
        logger.error("expired certificate", e);
        throw e;
    } catch (CertificateNotYetValidException e) {
        logger.error("certificate is not yet valid (may still need to be activated?)", e);
        throw e;
    } catch (CMSException e) {
        logger.error("error adding certificates to signature generator", e);
        throw new CryptoException("CMS error", e);
    }
}

From source file:org.dihedron.crypto.operations.sign.pkcs7.PKCS7SigningStream.java

License:Open Source License

/**
 * Constructor./*from  w  w w . j  a  v a2s  .  co  m*/
 * 
 * @param output
 *   the output stream to which data will be eventually written.
 * @param configurator
 *   the output signing stream configurator.
 * @throws CryptoException
 *   if any of the input parameters is null.
 * @throws CertificateNotYetValidException 
 * @throws CertificateExpiredException 
 * @throws GeneralSecurityException 
 */
public PKCS7SigningStream(OutputStream output, SigningStreamConfigurator configurator)
        throws CryptoException, CertificateExpiredException, CertificateNotYetValidException,
        CertificateEncodingException, GeneralSecurityException {
    super(output, configurator);

    logger.info(
            "creating PKCS#7 signing filter output stream with '{}' signature algorithm, using certificate alias '{}'",
            configurator.getAlgorithm(), configurator.getAlias());

    try {
        logger.info("signing with alias '{}'", configurator.getAlias());

        // retrieve key, certificate and provider (for simplicity)
        Key key = configurator.getPrivateKey();
        X509Certificate x509certificate = configurator.getCertificate();
        Provider provider = configurator.getProvider();
        SignatureAlgorithm algorithm = configurator.getAlgorithm();

        // prepare the certificates store
        List<Certificate> certificates = new ArrayList<>();
        certificates.add(x509certificate);
        Store store = new JcaCertStore(certificates);

        logger.info("certificate store is ready");

        ContentSigner signer = new JcaContentSignerBuilder(algorithm.toBouncyCastleCode())
                .setProvider((provider instanceof AutoCloseableProvider)
                        ? ((AutoCloseableProvider) provider).getWrappedProvider()
                        : provider)
                .build((PrivateKey) key);

        DigestCalculatorProvider digest = new JcaDigestCalculatorProviderBuilder().setProvider("BC").build();

        SignerInfoGenerator signerinfo = new SignerInfoGeneratorBuilder(digest).setDirectSignature(false) // include signed attributes; if true it signs data only
                .setSignedAttributeGenerator(
                        new PKCS7AttributeTableGenerator(algorithm.getDigestAlgorithm(), x509certificate)) // this generates the attributes that will be signed along with the data
                .build(signer, new JcaX509CertificateHolder(x509certificate)); // and then we build the generator

        logger.info("signer info generator is ready");

        generator = new CMSSignedDataStreamGenerator();
        generator.addSignerInfoGenerator(signerinfo);
        generator.addCertificates(store);
        //generator.addCRLs(crlStore);

        logger.debug("signed data stream generator for PKCS#7 is ready");

        stream = generator.open(output, configurator.isEncapsulateData());

    } catch (OperatorCreationException e) {
        logger.error("error creating operator", e);
        throw new CryptoException("error creating signing operator (BouncyCastle)", e);
    } catch (CertificateEncodingException e) {
        logger.error("invalid certificate encoding", e);
        throw e;
    } catch (CMSException e) {
        logger.error("error adding certificates to signature generator", e);
        throw new CryptoException("CMS error", e);
    } catch (IOException e) {
        logger.error("error establishing signature generator wrapper around output stream", e);
        throw new CryptoException("Error establishing signature generator wrapper around output stream", e);
    }
}

From source file:org.ejbca.util.CMS.java

License:Open Source License

/**
 * @param is data to be signed// www  .j av  a  2s  . c  om
 * @param os signed data
 * @param key to do be used for signing
 * @param providerName the provider that should do the signing
 * @throws Exception
 */
public static void sign(final InputStream is, OutputStream os, PrivateKey key, String providerName,
        X509Certificate cert) throws Exception {
    final InputStream bis = new BufferedInputStream(is, bufferSize);
    final OutputStream bos = new BufferedOutputStream(os, bufferSize);
    final CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator();
    JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
            .setProvider(BouncyCastleProvider.PROVIDER_NAME);
    JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
            calculatorProviderBuilder.build());
    final String digest = CMSSignedGenerator.DIGEST_SHA256;
    String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digest, key.getAlgorithm());
    ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName).setProvider(providerName)
            .build(key);
    if (cert != null) {
        gen.addSignerInfoGenerator(builder.build(contentSigner, cert));
    } else {
        gen.addSignerInfoGenerator(builder.build(contentSigner, "hej".getBytes()));
    }
    final OutputStream out = gen.open(bos, true);
    fromInToOut(bis, out);
    bos.close();
    os.close();
}

From source file:org.neociclo.odetteftp.util.EnvelopingUtil.java

License:Apache License

public static OutputStream openSignedDataStreamGenerator(OutputStream outStream, CipherSuite cipherSuite,
        X509Certificate cert, PrivateKey key) throws NoSuchAlgorithmException, NoSuchProviderException,
        CMSException, IOException, InvalidKeyException {

    installBouncyCastleProviderIfNecessary();

    // set up the generator
    CMSSignedDataStreamGenerator gen = new CMSSignedDataStreamGenerator();

    gen.addSigner(key, cert, asDigestAlgorithm(cipherSuite), BC_PROVIDER);

    // create the signed-data stream
    OutputStream signed = gen.open(outStream, true);

    return signed;
}