Example usage for org.bouncycastle.cms CMSSignedData getEncoded

List of usage examples for org.bouncycastle.cms CMSSignedData getEncoded

Introduction

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

Prototype

public byte[] getEncoded() throws IOException 

Source Link

Document

return the ASN.1 encoded representation of this object.

Usage

From source file:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to create exCap's signature with the issuer certificate detached 
 * from the signed data /*from   ww w .  j a  v  a  2  s  .  c o m*/
 * @param credentials: the credential that contains private key to sign the
 * data
 * @param content: the data or content to be signed
 * @return: signed data in byte[]
 * @throws OperatorCreationException
 * @throws CMSException
 * @throws IOException
 */
public static byte[] createCapSignature(BcCredential credentials, String content)
        throws OperatorCreationException, CMSException, IOException {

    AsymmetricKeyParameter key = credentials.getPrivateKey();
    X509CertificateHolder[] chain = credentials.getCertificateChain();

    X509CertificateHolder cert = chain[0];
    //    Store certs = new CollectionStore(Arrays.asList(chain));

    // construct SignerInfoGenerator manually --> to deal with signingTime issue
    SignerInfoGeneratorBuilder sigBuilder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider());

    Hashtable<ASN1ObjectIdentifier, Attribute> signedAttr = new Hashtable<ASN1ObjectIdentifier, Attribute>();

    Attribute attr = new Attribute(CMSAttributes.signingTime, new DERSet(new Time(new java.util.Date())));

    signedAttr.put(attr.getAttrType(), attr);
    AttributeTable signedAttributeTable = new AttributeTable(signedAttr);

    sigBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttributeTable));

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

    AlgorithmIdentifier sigAlg = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withECDSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    SignerInfoGenerator signerInfoGen = sigBuilder
            .build(new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(key), cert);

    gen.addSignerInfoGenerator(signerInfoGen);

    //    gen.addSignerInfoGenerator(new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()).build(new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(key), cert));
    // do not store the certificate with signed data (i.e. detached signature)
    //    gen.addCertificates(certs);

    // create the signed-data object
    CMSTypedData data = new CMSProcessableByteArray(content.getBytes());

    CMSSignedData signed = gen.generate(data);

    // recreate
    //    signed = new CMSSignedData(data, signed.getEncoded());

    return signed.getEncoded();
}

From source file:eu.europa.ec.markt.dss.DSSASN1Utils.java

License:Open Source License

/**
 * Returns the ASN.1 encoded representation of {@code CMSSignedData}.
 *
 * @param data/* w w  w  .  ja  v a 2 s.com*/
 * @return
 * @throws DSSException
 */
public static byte[] getEncoded(final CMSSignedData data) throws DSSException {

    try {
        return data.getEncoded();
    } catch (IOException e) {
        throw new DSSException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.cades.CAdESSignatureExtension.java

License:Open Source License

public static ASN1Object getTimeStampAttributeValue(final TSPSource tspSource, final byte[] messageToTimestamp,
        final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) {
    try {/*w  w w .j a  v a 2 s . c om*/

        if (LOG.isDebugEnabled()) {
            LOG.debug("Message to timestamp is: " + DSSUtils.encodeHexString(messageToTimestamp));
        }
        byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Digested ({}) message to timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, DSSUtils.encodeHexString(timestampDigest) });
        }

        final TimeStampToken timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm,
                timestampDigest);

        if (timeStampToken == null) {
            throw new DSSNullReturnedException(TimeStampToken.class);
        }

        if (LOG.isDebugEnabled()) {
            final byte[] messageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
            LOG.debug("Digested ({}) message in timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, DSSUtils.encodeHexString(messageImprintDigest) });
        }

        CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getEncoded());

        // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
        if (attributesForTimestampToken != null) {
            // timeStampToken contains one and only one signer
            final SignerInformation signerInformation = (SignerInformation) cmsSignedDataTimeStampToken
                    .getSignerInfos().getSigners().iterator().next();
            AttributeTable unsignedAttributes = CAdESSignature.getUnsignedAttributes(signerInformation);
            for (final Attribute attributeToAdd : attributesForTimestampToken) {
                final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
                final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
                unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
            }
            final SignerInformation newSignerInformation = SignerInformation
                    .replaceUnsignedAttributes(signerInformation, unsignedAttributes);
            final List<SignerInformation> signerInformationList = new ArrayList<SignerInformation>();
            signerInformationList.add(newSignerInformation);
            final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
            cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken,
                    newSignerStore);
        }
        final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
        return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }

}

From source file:eu.europa.ec.markt.dss.signature.pades.PAdESServiceV2.java

License:Open Source License

@Override
public Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue)
        throws IOException {
    try {//from w  w w  . java2  s.  co  m

        PAdESProfileEPES padesProfile = new PAdESProfileEPES();

        PreComputedContentSigner contentSigner = new PreComputedContentSigner(
                SignatureAlgorithm.RSA.getJavaSignatureAlgorithm(parameters.getDigestAlgorithm()),
                signatureValue);
        DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();

        PDFSignatureService pdfSignatureService = new ITextPDFSignatureService();
        byte[] messageDigest = pdfSignatureService.digest(document.openStream(), parameters);

        CMSSignedDataGenerator generator = padesProfile.createCMSSignedDataGenerator(contentSigner,
                digestCalculatorProvider, parameters, messageDigest);

        CMSProcessableByteArray content = new CMSProcessableByteArray(messageDigest);

        CMSSignedData data = generator.generate(content, false);
        if (tspSource != null) {
            CAdESProfileT t = new CAdESProfileT();
            t.setSignatureTsa(tspSource);
            data = t.extendCMSSignedData(data, null, parameters);
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        pdfSignatureService.sign(document.openStream(), data.getEncoded(), output, parameters);
        output.close();

        Document doc = new InMemoryDocument(output.toByteArray());

        PAdESProfileLTV extension = getExtensionProfile(parameters);
        if (extension != null) {
            return extension.extendSignatures(doc, null, parameters);
        } else {
            return doc;
        }

    } catch (DocumentException ex) {
        throw new IOException(ex);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.europa.ec.markt.dss.signature.pades.StatefulPAdESServiceV2.java

License:Open Source License

@Override
public Document signDocument(Document document, SignatureParameters parameters, byte[] signatureValue)
        throws IOException {
    try {/*from w  w w.jav  a 2 s .c  om*/

        PAdESProfileEPES padesProfile = new PAdESProfileEPES();

        PreComputedContentSigner contentSigner = new PreComputedContentSigner(
                SignatureAlgorithm.RSA.getJavaSignatureAlgorithm(parameters.getDigestAlgorithm()),
                signatureValue);
        DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();

        PDFSignatureService pdfSignatureService = getPDFService();
        byte[] messageDigest = pdfSignatureService.digest(document.openStream(), parameters);

        CMSSignedDataGenerator generator = padesProfile.createCMSSignedDataGenerator(contentSigner,
                digestCalculatorProvider, parameters, messageDigest);

        CMSProcessableByteArray content = new CMSProcessableByteArray(messageDigest);

        CMSSignedData data = generator.generate(content, false);
        if (tspSource != null) {
            CAdESProfileT t = new CAdESProfileT();
            t.setSignatureTsa(tspSource);
            data = t.extendCMSSignedData(data, null, parameters);
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream();

        pdfSignatureService.sign(document.openStream(), data.getEncoded(), output, parameters);
        output.close();

        Document doc = new InMemoryDocument(output.toByteArray());

        PAdESProfileLTV extension = getExtensionProfile(parameters);
        if (extension != null) {
            return extension.extendSignatures(doc, null, parameters);
        } else {
            return doc;
        }

    } catch (DocumentException ex) {
        throw new IOException(ex);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.europa.esig.dss.cades.signature.CAdESSignatureExtension.java

License:Open Source License

public static ASN1Object getTimeStampAttributeValue(final TSPSource tspSource, final byte[] messageToTimestamp,
        final DigestAlgorithm timestampDigestAlgorithm, final Attribute... attributesForTimestampToken) {
    try {/*from  w  ww  .j ava  2  s  . com*/

        if (LOG.isDebugEnabled()) {
            LOG.debug("Message to timestamp is: " + Hex.encodeHexString(messageToTimestamp));
        }
        byte[] timestampDigest = DSSUtils.digest(timestampDigestAlgorithm, messageToTimestamp);
        if (LOG.isDebugEnabled()) {
            LOG.debug("Digested ({}) message to timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, Hex.encodeHexString(timestampDigest) });
        }

        final TimeStampToken timeStampToken = tspSource.getTimeStampResponse(timestampDigestAlgorithm,
                timestampDigest);

        if (timeStampToken == null) {
            throw new NullPointerException();
        }

        if (LOG.isDebugEnabled()) {
            final byte[] messageImprintDigest = timeStampToken.getTimeStampInfo().getMessageImprintDigest();
            LOG.debug("Digested ({}) message in timestamp is {}",
                    new Object[] { timestampDigestAlgorithm, Hex.encodeHexString(messageImprintDigest) });
        }

        CMSSignedData cmsSignedDataTimeStampToken = new CMSSignedData(timeStampToken.getEncoded());

        // TODO (27/08/2014): attributesForTimestampToken cannot be null: to be modified
        if (attributesForTimestampToken != null) {
            // timeStampToken contains one and only one signer
            final SignerInformation signerInformation = cmsSignedDataTimeStampToken.getSignerInfos()
                    .getSigners().iterator().next();
            AttributeTable unsignedAttributes = CMSUtils.getUnsignedAttributes(signerInformation);
            for (final Attribute attributeToAdd : attributesForTimestampToken) {
                final ASN1ObjectIdentifier attrType = attributeToAdd.getAttrType();
                final ASN1Encodable objectAt = attributeToAdd.getAttrValues().getObjectAt(0);
                unsignedAttributes = unsignedAttributes.add(attrType, objectAt);
            }
            final SignerInformation newSignerInformation = SignerInformation
                    .replaceUnsignedAttributes(signerInformation, unsignedAttributes);
            final List<SignerInformation> signerInformationList = new ArrayList<SignerInformation>();
            signerInformationList.add(newSignerInformation);
            final SignerInformationStore newSignerStore = new SignerInformationStore(signerInformationList);
            cmsSignedDataTimeStampToken = CMSSignedData.replaceSigners(cmsSignedDataTimeStampToken,
                    newSignerStore);
        }
        final byte[] newTimeStampTokenBytes = cmsSignedDataTimeStampToken.getEncoded();
        return DSSASN1Utils.toASN1Primitive(newTimeStampTokenBytes);
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }

}

From source file:fixture.pdfboxeg.CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation.//from  ww  w  . j a  va  2s .co m
 *
 * This method will be called from inside of the pdfbox and create the PKCS #7 signature.
 * The given InputStream contains the bytes that are given by the byte range.
 *
 * This method is for internal use only.
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 *
 * @throws IOException
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    //TODO this method should be private
    try {
        List<Certificate> certList = new ArrayList<>();
        certList.add(certificate);
        Store certs = new JcaCertStore(certList);
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        org.bouncycastle.asn1.x509.Certificate cert = org.bouncycastle.asn1.x509.Certificate
                .getInstance(ASN1Primitive.fromByteArray(certificate.getEncoded()));
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA256WithRSA").build(privateKey);
        gen.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder().build())
                        .build(sha1Signer, new X509CertificateHolder(cert)));
        gen.addCertificates(certs);
        CMSProcessableInputStream msg = new CMSProcessableInputStream(content);
        CMSSignedData signedData = gen.generate(msg, false);
        if (tsaClient != null) {
            signedData = signTimeStamps(signedData);
        }
        return signedData.getEncoded();
    } catch (GeneralSecurityException | CMSException | TSPException | OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:id.govca.detachedsignature.FileHelper.java

public static byte[] CMStoDER(CMSSignedData sigData) throws IOException {
    ByteArrayInputStream inStream = new ByteArrayInputStream(sigData.getEncoded());
    ASN1InputStream asnInputStream = new ASN1InputStream(inStream);

    ASN1Primitive asp = asnInputStream.readObject();
    byte[] result = asp.getEncoded("DER");

    return result;
}

From source file:io.aos.crypto.spl09.EncapsulatedSignedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");

    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    gen.addSigner(key, (X509Certificate) chain[0], CMSSignedDataGenerator.DIGEST_SHA224);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    // create the signed-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSSignedData signed = gen.generate(data, true, "BC");

    // recreate/*from  www .  j  a  v a 2  s. c  om*/
    signed = new CMSSignedData(signed.getEncoded());

    // verification step
    X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

    if (isValid(signed, rootCert)) {
        System.out.println("signed-data verification succeeded");
    } else {
        System.out.println("signed-data verification failed");
    }
}

From source file:io.aos.crypto.spl09.SignedDataExample.java

License:Apache License

public static void main(String... args) throws Exception {
    KeyStore credentials = Utils.createCredentials();
    PrivateKey key = (PrivateKey) credentials.getKey(Utils.END_ENTITY_ALIAS, Utils.KEY_PASSWD);
    Certificate[] chain = credentials.getCertificateChain(Utils.END_ENTITY_ALIAS);
    CertStore certsAndCRLs = CertStore.getInstance("Collection",
            new CollectionCertStoreParameters(Arrays.asList(chain)), "BC");
    X509Certificate cert = (X509Certificate) chain[0];

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

    gen.addSigner(key, cert, CMSSignedDataGenerator.DIGEST_SHA224);

    gen.addCertificatesAndCRLs(certsAndCRLs);

    // create the signed-data object
    CMSProcessable data = new CMSProcessableByteArray("Hello World!".getBytes());

    CMSSignedData signed = gen.generate(data, "BC");

    // recreate//from   w w  w  .  j a  va  2 s .  c  om
    signed = new CMSSignedData(data, signed.getEncoded());

    // verification step
    X509Certificate rootCert = (X509Certificate) credentials.getCertificate(Utils.ROOT_ALIAS);

    if (isValid(signed, rootCert)) {
        System.out.println("verification succeeded");
    } else {
        System.out.println("verification failed");
    }
}