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:ch.cyberduck.core.aquaticprime.ReceiptVerifier.java

License:Open Source License

@Override
public boolean verify() {
    try {//from  w w w  .  jav a  2  s. co m
        // For additional security, you may verify the fingerprint of the root CA and the OIDs of the
        // intermediate CA and signing certificate. The OID in the Certificate Policies Extension of the
        // intermediate CA is (1 2 840 113635 100 5 6 1), and the Marker OID of the signing certificate
        // is (1 2 840 113635 100 6 11 1).
        final CMSSignedData s = new CMSSignedData(new FileInputStream(file.getAbsolute()));
        Store certs = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        for (SignerInformation signer : (Iterable<SignerInformation>) signers.getSigners()) {
            final Collection<X509CertificateHolder> matches = certs.getMatches(signer.getSID());
            for (X509CertificateHolder holder : matches) {
                if (!signer.verify(new JcaSimpleSignerInfoVerifierBuilder()
                        .setProvider(new BouncyCastleProvider()).build(holder))) {
                    return false;
                }
            }
        }
        // Extract the receipt attributes
        final CMSProcessable signedContent = s.getSignedContent();
        byte[] originalContent = (byte[]) signedContent.getContent();
        final ASN1Primitive asn = ASN1Primitive.fromByteArray(originalContent);

        byte[] opaque = null;
        String bundleIdentifier = null;
        String bundleVersion = null;
        byte[] hash = null;

        if (asn instanceof ASN1Set) {
            // 2 Bundle identifier      Interpret as an ASN.1 UTF8STRING.
            // 3 Application version    Interpret as an ASN.1 UTF8STRING.
            // 4 Opaque value           Interpret as a series of bytes.
            // 5 SHA-1 hash             Interpret as a 20-byte SHA-1 digest value.
            final ASN1Set set = (ASN1Set) asn;
            final Enumeration enumeration = set.getObjects();
            while (enumeration.hasMoreElements()) {
                Object next = enumeration.nextElement();
                if (next instanceof DLSequence) {
                    DLSequence sequence = (DLSequence) next;
                    ASN1Encodable type = sequence.getObjectAt(0);
                    if (type instanceof ASN1Integer) {
                        if (((ASN1Integer) type).getValue().intValue() == 2) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleIdentifier = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 3) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                bundleVersion = new String(((DEROctetString) value).getOctets(), "UTF-8");
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 4) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                opaque = ((DEROctetString) value).getOctets();
                            }
                        } else if (((ASN1Integer) type).getValue().intValue() == 5) {
                            final ASN1Encodable value = sequence.getObjectAt(2);
                            if (value instanceof DEROctetString) {
                                hash = ((DEROctetString) value).getOctets();
                            }
                        }
                    }
                }
            }
        } else {
            log.error(String.format("Expected set of attributes for %s", asn));
            return false;
        }
        if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.identifier"),
                StringUtils.trim(bundleIdentifier))) {
            log.error(String.format("Bundle identifier %s in ASN set does not match", bundleIdentifier));
            return false;
        }
        if (!StringUtils.equals(PreferencesFactory.get().getDefault("application.version"),
                StringUtils.trim(bundleVersion))) {
            log.warn(String.format("Bundle version %s in ASN set does not match", bundleVersion));
        }
        final NetworkInterface en0 = NetworkInterface.getByName("en0");
        if (null == en0) {
            // Interface is not found when link is down #fail
            log.warn("No network interface en0");
            return true;
        } else {
            final byte[] mac = en0.getHardwareAddress();
            if (null == mac) {
                log.error("Cannot determine MAC address");
                // Continue without validation
                return true;
            }
            final String hex = Hex.encodeHexString(mac);
            if (log.isDebugEnabled()) {
                log.debug(String.format("Interface en0 %s", hex));
            }
            // Compute the hash of the GUID
            final MessageDigest digest = MessageDigest.getInstance("SHA-1");
            digest.update(mac);
            if (null == opaque) {
                log.error(String.format("Missing opaque string in ASN.1 set %s", asn));
                return false;
            }
            digest.update(opaque);
            if (null == bundleIdentifier) {
                log.error(String.format("Missing bundle identifier in ASN.1 set %s", asn));
                return false;
            }
            digest.update(bundleIdentifier.getBytes(Charset.forName("UTF-8")));
            final byte[] result = digest.digest();
            if (Arrays.equals(result, hash)) {
                if (log.isInfoEnabled()) {
                    log.info(String.format("Valid receipt for GUID %s", hex));
                }
                guid = hex;
                return true;
            } else {
                log.error(String.format("Failed verification. Hash with GUID %s does not match hash in receipt",
                        hex));
                return false;
            }
        }
    } catch (IOException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (GeneralSecurityException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (SecurityException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (CMSException e) {
        log.error("Receipt validation error", e);
        // Shutdown if receipt is not valid
        return false;
    } catch (Exception e) {
        log.error("Unknown receipt validation error", e);
        return true;
    }
}

From source file:com.indivica.olis.Driver.java

License:Open Source License

public static String unsignData(String data) {

    byte[] dataBytes = Base64.decode(data);

    try {//from  www  .  j  a  v  a2  s  .com

        CMSSignedData s = new CMSSignedData(dataBytes);
        CertStore certs = s.getCertificatesAndCRLs("Collection", "BC");
        SignerInformationStore signers = s.getSignerInfos();
        @SuppressWarnings("unchecked")
        Collection<SignerInformation> c = signers.getSigners();
        Iterator<SignerInformation> it = c.iterator();
        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = it.next();
            Collection certCollection = certs.getCertificates(signer.getSID());
            @SuppressWarnings("unchecked")
            Iterator<X509Certificate> certIt = certCollection.iterator();
            cert = certIt.next();
            if (!signer.verify(cert.getPublicKey(), "BC"))
                throw new Exception("Doesn't verify");
        }

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] signedContent = (byte[]) cpb.getContent();
        String content = new String(signedContent);
        return content;
    } catch (Exception e) {
        MiscUtils.getLogger().error("error", e);
    }
    return null;

}

From source file:com.infinities.keystone4j.utils.Cms.java

License:Apache License

@SuppressWarnings("rawtypes")
public String verifySignature(byte[] sigbytes, String signingCertFileName, String caFileName)
        throws CMSException, CertificateException, OperatorCreationException, NoSuchAlgorithmException,
        NoSuchProviderException, CertPathBuilderException, InvalidAlgorithmParameterException, IOException,
        CertificateVerificationException {
    logger.debug("signingCertFile: {}, caFile:{}", new Object[] { signingCertFileName, caFileName });
    Security.addProvider(new BouncyCastleProvider());
    X509Certificate signercert = generateCertificate(signingCertFileName);
    X509Certificate cacert = generateCertificate(caFileName);
    Set<X509Certificate> additionalCerts = new HashSet<X509Certificate>();
    additionalCerts.add(cacert);// w w w  . j  av  a  2 s.  co  m

    CertificateVerifier.verifyCertificate(signercert, additionalCerts, true); // .validateKeyChain(signercert,
    // certs);
    if (Base64Verifier.isBase64(sigbytes)) {
        try {
            sigbytes = Base64.decode(sigbytes);
            logger.debug("Signature file is BASE64 encoded");
        } catch (Exception ioe) {
            logger.warn("Problem decoding from b64", ioe);
        }
    }

    // sigbytes = Base64.decode(sigbytes);

    // --- Use Bouncy Castle provider to verify included-content CSM/PKCS#7
    // signature ---
    ASN1InputStream in = null;
    try {
        logger.debug("sigbytes size: {}", sigbytes.length);
        in = new ASN1InputStream(new ByteArrayInputStream(sigbytes), Integer.MAX_VALUE);

        CMSSignedData s = new CMSSignedData(ContentInfo.getInstance(in.readObject()));
        Store store = s.getCertificates();
        SignerInformationStore signers = s.getSignerInfos();
        Collection c = signers.getSigners();
        Iterator it = c.iterator();
        int verified = 0;

        while (it.hasNext()) {
            X509Certificate cert = null;
            SignerInformation signer = (SignerInformation) it.next();
            Collection certCollection = store.getMatches(signer.getSID());
            if (certCollection.isEmpty() && signercert == null)
                continue;
            else if (signercert != null) // use a signer cert file for
                // verification, if it was
                // provided
                cert = signercert;
            else { // use the certificates included in the signature for
                   // verification
                Iterator certIt = certCollection.iterator();
                cert = (X509Certificate) certIt.next();
            }

            // if (signer.verify(new
            // JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(cert)))
            // verified++;
        }

        if (verified == 0) {
            logger.warn(" No signers' signatures could be verified !");
        } else if (signercert != null)
            logger.info("Verified a signature using signer certificate file  {}", signingCertFileName);
        else
            logger.info("Verified a signature using a certificate in the signature data");

        CMSProcessableByteArray cpb = (CMSProcessableByteArray) s.getSignedContent();
        byte[] rawcontent = (byte[]) cpb.getContent();

        return new String(rawcontent);
    } catch (Exception ex) {
        logger.error("Couldn't verify included-content CMS signature", ex);
        throw new RuntimeException("Couldn't verify included-content CMS signature", ex);
    } finally {
        if (in != null) {
            in.close();
        }
    }
}

From source file:com.miguelpazo.signature.test.SignDataTest.java

public String signDataWithPfx(String data, File certPfx, String pass, File dataSignedFile) throws Exception {
    KeyStore ks = KeyStore.getInstance("pkcs12");
    ks.load(new FileInputStream(certPfx), pass.toCharArray());
    String alias = (String) ks.aliases().nextElement();

    PrivateKey key = (PrivateKey) ks.getKey(alias, pass.toCharArray());
    Certificate[] chain = ks.getCertificateChain(alias);

    Signature signature = Signature.getInstance("SHA1WithRSA", "BC");
    signature.initSign(key);//w w  w. j  av  a 2  s  .  co m
    //        signature.update(Base64.encode(data.getBytes()));
    signature.update(data.getBytes());

    //Build CMS
    X509Certificate cert = (X509Certificate) ks.getCertificate(alias);
    List certList = new ArrayList();
    CMSTypedData msg = new CMSProcessableByteArray(signature.sign());
    certList.add(cert);

    Store certs = new JcaCertStore(certList);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1WithRSA").setProvider("BC").build(key);
    gen.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider("BC").build()).build(sha1Signer, cert));
    gen.addCertificates(certs);

    CMSSignedData sigData = gen.generate(msg, false);
    byte[] dataSigned = Base64.encode(sigData.getEncoded());
    String envelopedData = new String(dataSigned);

    certUtil.exportToFile(envelopedData, dataSignedFile);

    byte[] b = (byte[]) sigData.getSignedContent().getContent();
    String dataEncrypt = new String(Base64.encode(b));

    System.out.println("content => " + dataEncrypt);

    PublicKey pubKey = cert.getPublicKey();
    String dataFinal = certUtil.decryptData(pubKey, dataEncrypt);

    System.out.println(dataEncrypt);
    //        System.out.println(dataFinal);

    return envelopedData;
}

From source file:com.miguelpazo.signature.test.SignDataTest.java

public void verifyData(String envelopedData) throws Exception {
    CMSSignedData cms = new CMSSignedData(Base64.decode(envelopedData.getBytes()));
    Store store = cms.getCertificates();

    SignerInformationStore signers = cms.getSignerInfos();
    Collection c = signers.getSigners();
    Iterator it = c.iterator();// w ww  .  j av  a2s.com

    //        Object content = cms.getSignedContent().getContent();
    //        byte[] b = (byte[]) content;
    //        byte[] dataSigned = Base64.encode(cms.getSignedContent());
    System.out.println(cms.getSignedContent());

    while (it.hasNext()) {
        SignerInformation signer = (SignerInformation) it.next();
        Collection certCollection = store.getMatches(signer.getSID());
        Iterator certIt = certCollection.iterator();

        X509CertificateHolder certHolder = (X509CertificateHolder) certIt.next();
        X509Certificate certFromSignedData = new JcaX509CertificateConverter().setProvider("BC")
                .getCertificate(certHolder);

        System.out.println("data => " + certFromSignedData.getSubjectDN().toString());

        //            byte[] data = Base64.encode(signer.getContentDigest());
        //            System.out.println(new String(data));
        //            if (signer.verify(new JcaSimpleSignerInfoVerifierBuilder().setProvider("BC").build(certFromSignedData))) {
        //                System.out.println("Signature verified");
        //            } else {
        //                System.out.println("Signature verification failed");
        //            }
    }
}

From source file:com.yacme.ext.oxsit.cust_it.security.crl.CertificationAuthorities.java

License:Open Source License

private static InputStream getCmsInputStream(URL url) {

    ByteArrayInputStream bais = null;
    try {/*from  w ww . ja va 2  s.c o  m*/
        CMSSignedData cms = new CMSSignedData(url.openStream());

        cms.getSignedContent();
        ByteArrayOutputStream baos = new ByteArrayOutputStream();
        cms.getSignedContent().write(baos);
        bais = new ByteArrayInputStream(baos.toByteArray());
    } catch (CMSException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return bais;
}

From source file:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java

License:Open Source License

public byte[] verify(byte[] signedBytes) throws SignatureVerificationException {
    try {//from  w ww .ja v a 2s. c  om
        Signature sig = Signature.getInstance("Sha1withRSAEncryption");
        CMSSignedData signedData = new CMSSignedData(signedBytes);
        CertStore certs = signedData.getCertificatesAndCRLs("Collection", "BC");
        Collection<SignerInformation> signers = signedData.getSignerInfos().getSigners();
        for (SignerInformation signer : signers) {
            Collection<? extends Certificate> certCollection = certs.getCertificates(signer.getSID());
            if (!certCollection.isEmpty()) {
                X509Certificate cert = (X509Certificate) certCollection.iterator().next();
                if (!signer.verify(cert.getPublicKey(), "BC")) {
                    throw new SignatureVerificationException("La firma no verifico con " + signer.getSID());
                }
                setCert(cert);
            }
        }

        CMSProcessable signedContent = signedData.getSignedContent();
        System.out.println("Tiene:" + signedContent.getContent());
        return (byte[]) signedContent.getContent();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e); // FIXME

    } catch (CMSException e) {
        throw new RuntimeException(e); // FIXME

    }
}

From source file:ec.gov.informatica.firmadigital.signature.BouncyCastleSignatureProcessor.java

License:Open Source License

@Override
public byte[] addSignature(byte[] signedBytes, PrivateKey privateKey, Certificate[] chain) {
    X509Certificate cert = (X509Certificate) chain[0];

    try {//from   w  w  w .  ja v  a 2  s  .co m
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(privateKey, cert, CMSSignedDataGenerator.DIGEST_SHA1);

        CertStore certs = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(Arrays.asList(chain)));

        CMSSignedData signedData = new CMSSignedData(signedBytes);
        SignerInformationStore signers = signedData.getSignerInfos();
        CertStore existingCerts = signedData.getCertificatesAndCRLs("Collection", "BC");
        X509Store x509Store = signedData.getAttributeCertificates("Collection", "BC");

        // add new certs
        generator.addCertificatesAndCRLs(certs);
        // add existing certs
        generator.addCertificatesAndCRLs(existingCerts);
        // add existing certs attributes
        generator.addAttributeCertificates(x509Store);
        // add existing signers
        generator.addSigners(signers);

        CMSProcessable content = signedData.getSignedContent();
        signedData = generator.generate(content, true, "BC");
        return signedData.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    } catch (NoSuchStoreException e) {
        throw new RuntimeException(e);
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:eu.europa.ec.markt.dss.applet.WizardFinishedPanel.java

License:Open Source License

private void signAndSaveFile() throws NoSuchAlgorithmException, IOException {
    SignatureTokenConnection connection = null;

    DocumentSignatureService service = model.createDocumentSignatureService();

    Document document = model.getOriginalFile();

    SignatureParameters parameters = new SignatureParameters();
    parameters.setSigningDate(new Date());
    parameters.setSigningCertificate((X509Certificate) model.getPrivateKey().getCertificate());
    if (model.getPrivateKey().getCertificateChain() != null) {
        parameters.setCertificateChain(/*from   www . jav  a 2  s.c  o  m*/
                Arrays.asList((X509Certificate[]) model.getPrivateKey().getCertificateChain()));
    }
    parameters.setSignatureFormat(model.getSignatureFormat());
    parameters.setSignaturePackaging(model.getPackaging());
    parameters.setClaimedSignerRole(model.getClaimedRole());
    parameters.setSignaturePolicy(model.getSignaturePolicyType());
    parameters.setSignaturePolicyId(model.getSignaturePolicy());
    parameters.setSignaturePolicyHashValue(model.getSignaturePolicyValue());
    parameters.setSignaturePolicyHashAlgo(model.getSignaturePolicyAlgo());

    connection = model.createTokenConnection(getWizard());

    Document contentInCMS = null;
    if (service instanceof CAdESService
            && parameters.getSignaturePackaging() == SignaturePackaging.ENVELOPING) {

        FileInputStream original = null;
        try {
            CMSSignedData cmsData = new CMSSignedData(model.getOriginalFile().openStream());
            if (cmsData != null && cmsData.getSignedContent() != null
                    && cmsData.getSignedContent().getContent() != null) {
                ByteArrayOutputStream buf = new ByteArrayOutputStream();
                cmsData.getSignedContent().write(buf);
                contentInCMS = new InMemoryDocument(buf.toByteArray());
            }
        } catch (CMSException ex) {

        } finally {
            if (original != null) {
                original.close();
            }
        }
    }

    Document signedDocument = null;
    if (contentInCMS != null) {
        byte[] signatureValue = connection.sign(service.toBeSigned(contentInCMS, parameters),
                DigestAlgorithm.SHA1, model.getPrivateKey());
        CAdESService cadesService = (CAdESService) service;
        signedDocument = cadesService.addASignatureToDocument(document, parameters, signatureValue);
    } else {
        byte[] signatureValue = connection.sign(service.toBeSigned(document, parameters), DigestAlgorithm.SHA1,
                model.getPrivateKey());
        signedDocument = service.signDocument(document, parameters, signatureValue);
    }

    FileOutputStream output = new FileOutputStream(model.getSignedFile());
    IOUtils.copy(signedDocument.openStream(), output);
    output.close();

}

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

License:Open Source License

/**
 * If the {@code DSSDocument} is a CMS message and the signed content's content is not null then the {@code CMSSignedData} is returned.
 * All exceptions are hidden/*from ww  w.j  a va2s.c om*/
 *
 * @param dssDocument
 * @return {@code CMSSignedData} or {@code null}
 */
public static CMSSignedData getOriginalSignedData(final DSSDocument dssDocument) {

    CMSSignedData originalSignedData = null;

    try {
        // check if input toSignDocument is already signed
        originalSignedData = new CMSSignedData(dssDocument.getBytes());
        if (originalSignedData.getSignedContent().getContent() == null) {
            originalSignedData = null;
        }
    } catch (Exception e) {
        // not a parallel signature
    }
    return originalSignedData;
}