Example usage for org.bouncycastle.cms CMSSignedData getSignedContent

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

Introduction

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

Prototype

public CMSTypedData getSignedContent() 

Source Link

Usage

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

License:Open Source License

/**
 * Returns the original document which is signed, either from cmsSignedData if possible, or from parameters.getOriginalDocument
 *
 * @param cmsSignedData//from   ww w  .j  a va  2 s . co  m
 * @param parameters
 * @return
 * @throws eu.europa.ec.markt.dss.exception.DSSException
 */
private byte[] getOriginalDocumentBytes(CMSSignedData cmsSignedData, SignatureParameters parameters)
        throws DSSException {

    try {

        final ByteArrayOutputStream originalSignedFileByteArrayOutputStream = new ByteArrayOutputStream();
        if (cmsSignedData.getSignedContent() != null) {
            cmsSignedData.getSignedContent().write(originalSignedFileByteArrayOutputStream);
        } else {
            originalSignedFileByteArrayOutputStream.write(parameters.getDetachedContent().getBytes());
        }
        return originalSignedFileByteArrayOutputStream.toByteArray();
    } catch (IOException e) {
        throw new DSSException(e);
    } catch (CMSException e) {
        throw new DSSException(e);
    }
}

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

License:Open Source License

/**
 * This method countersigns a signature identified through its SignerId
 *
 * @param toCounterSignDocument the original signature document containing the signature to countersign
 * @param parameters            the signature parameters
 * @param selector              the SignerId identifying the signature to countersign
 * @return the updated signature document, in which the countersignature has been embedded
 *///w  w  w .j a v  a  2s  .c om
public DSSDocument counterSignDocument(final DSSDocument toCounterSignDocument,
        final SignatureParameters parameters, SignerId selector) {

    final SignatureTokenConnection token = parameters.getSigningToken();
    if (token == null) {

        throw new DSSNullException(SignatureTokenConnection.class, "",
                "The connection through available API to the SSCD must be set.");
    }

    try {
        //Retrieve the original signature
        final InputStream inputStream = toCounterSignDocument.openStream();
        final CMSSignedData cmsSignedData = new CMSSignedData(inputStream);
        DSSUtils.closeQuietly(inputStream);

        SignerInformationStore signerInfos = cmsSignedData.getSignerInfos();
        SignerInformation signerInformation = signerInfos.get(selector);

        //Generate a signed digest on the contents octets of the signature octet String in the identified SignerInfo value
        //of the original signature's SignedData
        byte[] dataToSign = signerInformation.getSignature();
        byte[] signatureValue = token.sign(dataToSign, parameters.getDigestAlgorithm(),
                parameters.getPrivateKeyEntry());

        //Set the countersignature builder
        CounterSignatureBuilder builder = new CounterSignatureBuilder(certificateVerifier);
        builder.setCmsSignedData(cmsSignedData);
        builder.setSelector(selector);

        final SignatureAlgorithm signatureAlgorithm = parameters.getSignatureAlgorithm();
        final CustomContentSigner customContentSigner = new CustomContentSigner(signatureAlgorithm.getJCEId(),
                signatureValue);

        SignerInfoGeneratorBuilder signerInformationGeneratorBuilder = builder
                .getSignerInfoGeneratorBuilder(parameters, true);
        CMSSignedDataGenerator cmsSignedDataGenerator = builder.createCMSSignedDataGenerator(parameters,
                customContentSigner, signerInformationGeneratorBuilder, null);
        CMSTypedData content = cmsSignedData.getSignedContent();
        CMSSignedData signedData = cmsSignedDataGenerator.generate(content);
        final CMSSignedData countersignedCMSData = builder.signDocument(signedData);
        final CMSSignedDocument signature = new CMSSignedDocument(countersignedCMSData);
        return signature;

    } catch (CMSException e) {
        throw new DSSException("Cannot parse CMS data", e);
    }
}

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

License:Open Source License

/**
 * This method returns the signed content of CMSSignedData.
 *
 * @param cmsSignedData the already signed {@code CMSSignedData}
 * @return the original toSignDocument or null
 *///from  www .  ja v a 2s .com
private DSSDocument getSignedContent(final CMSSignedData cmsSignedData) {

    if (cmsSignedData != null) {

        final CMSTypedData signedContent = cmsSignedData.getSignedContent();
        final byte[] documentBytes = (signedContent != null) ? (byte[]) signedContent.getContent() : null;
        final InMemoryDocument inMemoryDocument = new InMemoryDocument(documentBytes);
        return inMemoryDocument;
    }
    return null;
}

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

License:Open Source License

/**
 * In case of an enveloping signature if the signed content's content is null then the null is returned.
 *
 * @param dssDocument {@code DSSDocument} containing the data to be signed or {@code CMSSignedData}
 * @param parameters  set of driving signing parameters
 * @return the {@code CMSSignedData} if the dssDocument is an CMS signed message. Null otherwise.
 */// ww w . ja  v a2s .c  om
private CMSSignedData getCmsSignedData(final DSSDocument dssDocument, final SignatureParameters parameters) {

    CMSSignedData cmsSignedData = null;
    try {
        // check if input dssDocument is already signed
        cmsSignedData = new CMSSignedData(dssDocument.getBytes());
        final SignaturePackaging signaturePackaging = parameters.getSignaturePackaging();
        if (signaturePackaging == SignaturePackaging.ENVELOPING) {

            if (cmsSignedData.getSignedContent().getContent() == null) {
                cmsSignedData = null;
            }
        }
    } catch (Exception e) {
        // not a parallel signature
    }
    return cmsSignedData;
}

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

License:Open Source License

protected CMSSignedData regenerateCMSSignedData(CMSSignedData cmsSignedData, SignatureParameters parameters,
        Store certificatesStore, Store attributeCertificatesStore, Store crlsStore,
        Store otherRevocationInfoFormatStoreBasic, Store otherRevocationInfoFormatStoreOcsp) {
    try {//from  w w w .j  ava 2  s.c o m

        final CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
        cmsSignedDataGenerator.addSigners(cmsSignedData.getSignerInfos());
        cmsSignedDataGenerator.addAttributeCertificates(attributeCertificatesStore);
        cmsSignedDataGenerator.addCertificates(certificatesStore);
        cmsSignedDataGenerator.addCRLs(crlsStore);
        cmsSignedDataGenerator.addOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic,
                otherRevocationInfoFormatStoreBasic);
        cmsSignedDataGenerator.addOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response,
                otherRevocationInfoFormatStoreOcsp);
        final boolean encapsulate = cmsSignedData.getSignedContent() != null;
        if (!encapsulate) {
            final InputStream inputStream = parameters.getDetachedContent().openStream();
            final CMSProcessableByteArray content = new CMSProcessableByteArray(
                    DSSUtils.toByteArray(inputStream));
            DSSUtils.closeQuietly(inputStream);
            cmsSignedData = cmsSignedDataGenerator.generate(content, encapsulate);
        } else {
            cmsSignedData = cmsSignedDataGenerator.generate(cmsSignedData.getSignedContent(), encapsulate);
        }
        return cmsSignedData;
    } catch (CMSException e) {
        throw new DSSException(e);
    }
}

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

License:Open Source License

/**
 * Returns the original document which is signed, either from cmsSignedData if possible, or from {@code parameters.getDetachedContent()}
 *
 * @param cmsSignedData/*from  w w w.  ja v a 2 s.com*/
 * @param parameters
 * @return
 * @throws eu.europa.esig.dss.DSSException
 */
private InputStream getOriginalDocumentBytes(CMSSignedData cmsSignedData, CAdESSignatureParameters parameters)
        throws DSSException {

    final CMSTypedData signedContent = cmsSignedData.getSignedContent();
    if (signedContent != null) {
        return new ByteArrayInputStream(CMSUtils.getSignedContent(signedContent));
    }
    final DSSDocument detachedContent = parameters.getDetachedContent();
    if (detachedContent == null) {
        throw new DSSException("In the case of detached signature the detached content must be set!");
    }
    return detachedContent.openStream();
}

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

License:Open Source License

/**
 * This method returns the signed content of CMSSignedData.
 *
 * @param cmsSignedData//from ww w .j av  a 2s.co m
 *            the already signed {@code CMSSignedData}
 * @return the original toSignDocument or null
 */
private DSSDocument getSignedContent(final CMSSignedData cmsSignedData) {
    if (cmsSignedData != null) {
        final CMSTypedData signedContent = cmsSignedData.getSignedContent();
        final byte[] documentBytes = (signedContent != null) ? (byte[]) signedContent.getContent() : null;
        final InMemoryDocument inMemoryDocument = new InMemoryDocument(documentBytes);
        return inMemoryDocument;
    }
    return null;
}

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

License:Open Source License

/**
 * In case of an enveloping signature if the signed content's content is null then the null is returned.
 *
 * @param dssDocument/*from   ww  w . j  a v  a  2  s .  c  om*/
 *            {@code DSSDocument} containing the data to be signed or {@code CMSSignedData}
 * @param parameters
 *            set of driving signing parameters
 * @return the {@code CMSSignedData} if the dssDocument is an CMS signed message. Null otherwise.
 */
private CMSSignedData getCmsSignedData(final DSSDocument dssDocument,
        final CAdESSignatureParameters parameters) {

    CMSSignedData cmsSignedData = null;
    try {
        // check if input dssDocument is already signed
        cmsSignedData = new CMSSignedData(DSSUtils.toByteArray(dssDocument));
        final SignaturePackaging signaturePackaging = parameters.getSignaturePackaging();
        if (signaturePackaging == SignaturePackaging.ENVELOPING) {

            if (cmsSignedData.getSignedContent().getContent() == null) {
                cmsSignedData = null;
            }
        }
    } catch (Exception e) {
        // not a parallel signature
    }
    return cmsSignedData;
}

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

License:Open Source License

protected CMSSignedData regenerateCMSSignedData(CMSSignedData cmsSignedData,
        CAdESSignatureParameters parameters, Store certificatesStore, Store attributeCertificatesStore,
        Store crlsStore, Store otherRevocationInfoFormatStoreBasic, Store otherRevocationInfoFormatStoreOcsp) {
    try {/*  ww w  .  j av a  2 s  . co  m*/

        final CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
        cmsSignedDataGenerator.addSigners(cmsSignedData.getSignerInfos());
        cmsSignedDataGenerator.addAttributeCertificates(attributeCertificatesStore);
        cmsSignedDataGenerator.addCertificates(certificatesStore);
        cmsSignedDataGenerator.addCRLs(crlsStore);
        cmsSignedDataGenerator.addOtherRevocationInfo(id_pkix_ocsp_basic, otherRevocationInfoFormatStoreBasic);
        cmsSignedDataGenerator.addOtherRevocationInfo(id_ri_ocsp_response, otherRevocationInfoFormatStoreOcsp);
        final boolean encapsulate = cmsSignedData.getSignedContent() != null;
        if (!encapsulate) {
            final InputStream inputStream = parameters.getDetachedContent().openStream();
            final CMSProcessableByteArray content = new CMSProcessableByteArray(
                    DSSUtils.toByteArray(inputStream));
            IOUtils.closeQuietly(inputStream);
            cmsSignedData = cmsSignedDataGenerator.generate(content, encapsulate);
        } else {
            cmsSignedData = cmsSignedDataGenerator.generate(cmsSignedData.getSignedContent(), encapsulate);
        }
        return cmsSignedData;
    } catch (CMSException e) {
        throw new DSSException(e);
    }
}

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

public boolean VerifyCMS(CMSSignedData signedData, String content_digest) throws IOException, CMSException,
        CertificateException, OperatorCreationException, UnmatchedSignatureException, NoSuchAlgorithmException,
        NoSuchPaddingException, InvalidKeyException, IllegalBlockSizeException, BadPaddingException,
        StringFormatException, ParseException, GeneralSecurityException {
    rootCertCandidate = null;/*from  w ww  .ja v  a 2s.  c  o m*/

    Security.addProvider(new BouncyCastleProvider());

    byte[] dataku = (byte[]) signedData.getSignedContent().getContent();
    System.out.format("%-32s%s\n", "Base64 of Signed Content", Hex.toHexString(dataku));

    Store store = signedData.getCertificates();

    CertStore certsAndCRLs = new JcaCertStoreBuilder().setProvider("BC")
            .addCertificates(signedData.getCertificates()).build();

    // Verify signature
    SignerInformationStore signers = signedData.getSignerInfos();
    Collection c = signers.getSigners();
    System.out.format("%-32s%s\n", "Number of Signers", c.size());

    Iterator it = c.iterator();
    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        AttributeTable att = signer.getSignedAttributes();

        Attribute mdAtt = att.get(CMSAttributes.messageDigest);
        ASN1Primitive asp = mdAtt.getAttrValues().getObjectAt(0).toASN1Primitive();
        byte[] hasil = asp.getEncoded("DER");

        System.out.format("%-32s%s\n", "Digest of Signature", Hex.toHexString(hasil));

        Collection certCollection = store.getMatches(signer.getSID());
        JcaX509CertificateConverter converter = new JcaX509CertificateConverter().setProvider("BC");

        ArrayList<X509CertificateHolder> listCertDatFirm = new ArrayList(store.getMatches(null));
        System.out.format("%-32s%d\n", "Number of cert Holders All", listCertDatFirm.size());

        try {
            verifyChain(listCertDatFirm);
        } catch (CertificateVerificationException ex) {
            System.out.println("CERTIFICATE CHAIN VERIFICATION FAILED");
            Logger.getLogger(CMSController.class.getName()).log(Level.SEVERE, null, ex);
            throw new UnmatchedSignatureException("Certificate Chain verification failed");
        }
        System.out.println("CERTIFICATE CHAIN VERIFIED");

        Collection<X509CertificateHolder> holders = store.getMatches(signer.getSID());

        Iterator certIt = certCollection.iterator();
        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter()
                .setProvider(new BouncyCastleProvider()).getCertificate(certHolder);

        Principal princ = certFromSignedData.getIssuerDN();

        //Get Signer Name
        Principal p = certFromSignedData.getSubjectDN();
        System.out.format("%-32s%s\n", "Signer Distinguished Name", p.getName());

        this.setDN_fields(StringHelper.DNFieldsMapper(p.getName()));

        //Get Signing Time
        org.bouncycastle.asn1.cms.Attribute signingTime = att
                .get(new ASN1ObjectIdentifier("1.2.840.113549.1.9.5"));
        String asn1time = signingTime.getAttrValues().toString();
        System.out.format("%-32s%s\n", "Signing Time (RAW format)", asn1time);

        Date signtime = StringHelper.ASN1DateParser(asn1time);
        SimpleDateFormat formatter = new SimpleDateFormat("dd MMM yyyy hh:mm:ss zzz");
        String formattedDate = formatter.format(signtime);
        System.out.format("%-32s%s\n", "Signing Time (Pretty format)", formattedDate);

        PublicKey pubkey = certFromSignedData.getPublicKey();

        if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider(new BouncyCastleProvider())
                .build(certFromSignedData))) {
            System.out.println("SIGNATURE VERIFIED <BY BOUNCY CASTLE STANDARD>");
        } else {
            System.out.println("SIGNATURE VERIFICATION <BY BOUNCY CASTLE STANDARD> FAILED");
            throw new UnmatchedSignatureException(
                    "Signature verification failed, probably the signature (CMS) has been altered!");
        }

        Cipher RSADecrypter;

        RSADecrypter = Cipher.getInstance("RSA/ECB/PKCS1Padding", "BC");

        //Initialize the Cipher using our the first key in the keystore  works fine for both
        RSADecrypter.init(Cipher.DECRYPT_MODE, pubkey);
        byte[] try_decrypt = RSADecrypter.doFinal(dataku);

        String decrypt_result = Hex.toHexString(try_decrypt);
        //Because there is magic number for hash algorithm at the beginning of the string,
        //we only need the last 64 characters from the decryption result
        String sanitized_decrypt_result = decrypt_result.substring(decrypt_result.length() - 64);

        System.out.format("%-32s%s\n", "Decryption Result", decrypt_result);
        System.out.format("%-32s%s\n", "Sanitized Decryption Result", sanitized_decrypt_result);

        if (!content_digest.equals(sanitized_decrypt_result)) {
            System.out.println("CONTENT DIGEST VERIFICATION FAILED");
            throw new UnmatchedSignatureException(
                    "Content digest verification failed, probably the content has been altered!");
        }
        System.out.println("CONTENT DIGEST VERIFIED");

        try {
            RootCertChecker rc = new RootCertChecker();

            rc.checkCertificate(rootCertCandidate, getRoot_cert_path());
        } catch (FileNotFoundException | InvalidKeyException | NoSuchAlgorithmException
                | NoSuchProviderException | SignatureException | CertificateException ex) {
            System.out.println("ROOT CERT VERIFICATION FAILED");
            throw new UnmatchedSignatureException("The System does not recognized this root Certificate");
        }
        System.out.println("ROOT CERTIFICATE VERIFIED");

    }

    return true;
}