Example usage for org.bouncycastle.cms CMSProcessableByteArray CMSProcessableByteArray

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

Introduction

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

Prototype

public CMSProcessableByteArray(byte[] bytes) 

Source Link

Usage

From source file:assinaBc.java

byte[] signPkcs7(final byte[] content, final CMSSignedDataGenerator generator) throws Exception {

    CMSTypedData cmsdata = new CMSProcessableByteArray(content);
    CMSSignedData signeddata = generator.generate(cmsdata, true);
    return signeddata.getEncoded();
}

From source file:createSod.java

License:Open Source License

/**
 * @param args//from   w  ww.j  av a2s  .c  o m
 * @throws CMSException 
 */
public static void main(String[] args) throws Exception {

    try {
        CommandLine options = verifyArgs(args);
        String privateKeyLocation = options.getOptionValue("privatekey");
        String keyPassword = options.getOptionValue("keypass");
        String certificate = options.getOptionValue("certificate");
        String sodContent = options.getOptionValue("content");
        String sod = "";
        if (options.hasOption("out")) {
            sod = options.getOptionValue("out");
        }

        // CHARGEMENT DU FICHIER PKCS#12

        KeyStore ks = null;
        char[] password = null;

        Security.addProvider(new BouncyCastleProvider());
        try {
            ks = KeyStore.getInstance("PKCS12");
            // Password pour le fichier personnal_nyal.p12
            password = keyPassword.toCharArray();
            ks.load(new FileInputStream(privateKeyLocation), password);
        } catch (Exception e) {
            System.out.println("Erreur: fichier " + privateKeyLocation
                    + " n'est pas un fichier pkcs#12 valide ou passphrase incorrect");
            return;
        }

        // RECUPERATION DU COUPLE CLE PRIVEE/PUBLIQUE ET DU CERTIFICAT PUBLIQUE

        X509Certificate cert = null;
        PrivateKey privatekey = null;
        PublicKey publickey = null;

        try {
            Enumeration en = ks.aliases();
            String ALIAS = "";
            Vector vectaliases = new Vector();

            while (en.hasMoreElements())
                vectaliases.add(en.nextElement());
            String[] aliases = (String[]) (vectaliases.toArray(new String[0]));
            for (int i = 0; i < aliases.length; i++)
                if (ks.isKeyEntry(aliases[i])) {
                    ALIAS = aliases[i];
                    break;
                }
            privatekey = (PrivateKey) ks.getKey(ALIAS, password);
            cert = (X509Certificate) ks.getCertificate(ALIAS);
            publickey = ks.getCertificate(ALIAS).getPublicKey();
        } catch (Exception e) {
            e.printStackTrace();
            return;
        }

        // Chargement du certificat  partir du fichier

        InputStream inStream = new FileInputStream(certificate);
        CertificateFactory cf = CertificateFactory.getInstance("X.509");
        cert = (X509Certificate) cf.generateCertificate(inStream);
        inStream.close();

        // Chargement du fichier qui va tre sign

        File file_to_sign = new File(sodContent);
        byte[] buffer = new byte[(int) file_to_sign.length()];
        DataInputStream in = new DataInputStream(new FileInputStream(file_to_sign));
        in.readFully(buffer);
        in.close();

        // Chargement des certificats qui seront stocks dans le fichier .p7
        // Ici, seulement le certificat personnal_nyal.cer sera associ.
        // Par contre, la chane des certificats non.

        ArrayList certList = new ArrayList();
        certList.add(cert);
        CertStore certs = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList),
                "BC");

        CMSSignedDataGenerator signGen = new CMSSignedDataGenerator();

        // privatekey correspond  notre cl prive rcupre du fichier PKCS#12
        // cert correspond au certificat publique personnal_nyal.cer
        // Le dernier argument est l'algorithme de hachage qui sera utilis

        signGen.addSigner(privatekey, cert, CMSSignedDataGenerator.DIGEST_SHA1);
        signGen.addCertificatesAndCRLs(certs);
        CMSProcessable content = new CMSProcessableByteArray(buffer);

        // Generation du fichier CMS/PKCS#7
        // L'argument deux permet de signifier si le document doit tre attach avec la signature
        //     Valeur true:  le fichier est attach (c'est le cas ici)
        //     Valeur false: le fichier est dtach

        CMSSignedData signedData = signGen.generate(content, true, "BC");
        byte[] signeddata = signedData.getEncoded();

        // Ecriture du buffer dans un fichier.   

        if (sod.equals("")) {
            System.out.print(signeddata.toString());
        } else {
            FileOutputStream envfos = new FileOutputStream(sod);
            envfos.write(signeddata);
            envfos.close();
        }

    } catch (OptionException oe) {
        HelpFormatter formatter = new HelpFormatter();
        formatter.printHelp(NAME, getOptions());
        System.exit(-1);
    } catch (Exception e) {
        e.printStackTrace();
        return;
    }

}

From source file:be.e_contract.mycarenet.certra.cms.CMSSigner.java

License:Open Source License

private byte[] sign(byte[] data) throws SignatureException {
    CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
    try {//from   ww w .ja  v a  2  s .  c om
        ContentSigner contentSigner = new JcaContentSignerBuilder("SHA256withRSA").build(this.privateKey);
        cmsSignedDataGenerator.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build()).build(contentSigner,
                                this.certificateChain.get(0)));
        for (X509Certificate certificate : this.certificateChain) {
            cmsSignedDataGenerator.addCertificate(new X509CertificateHolder(certificate.getEncoded()));
        }
        CMSTypedData cmsTypedData = new CMSProcessableByteArray(data);
        CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true);
        return cmsSignedData.getEncoded();
    } catch (Exception e) {
        throw new SignatureException(e);
    }
}

From source file:be.e_contract.mycarenet.etee.Sealer.java

License:Open Source License

private byte[] encrypt(byte[] data) throws CertificateEncodingException, CMSException, IOException {
    CMSEnvelopedDataGenerator cmsEnvelopedDataGenerator = new CMSEnvelopedDataGenerator();
    for (X509Certificate destinationCertificate : this.destinationCertificates) {
        cmsEnvelopedDataGenerator// w  w w . j  a  v  a2 s  . c o m
                .addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(destinationCertificate)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME));
    }
    CMSTypedData cmsTypedData = new CMSProcessableByteArray(data);
    CMSEnvelopedData cmsEnvelopedData = cmsEnvelopedDataGenerator.generate(cmsTypedData,
            new JceCMSContentEncryptorBuilder(CMSAlgorithm.AES128_CBC)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME).build());
    return cmsEnvelopedData.getEncoded();
}

From source file:be.e_contract.mycarenet.etee.Sealer.java

License:Open Source License

private byte[] sign(byte[] data, boolean includeCertificate)
        throws OperatorCreationException, CertificateEncodingException, CMSException, IOException {
    CMSSignedDataGenerator cmsSignedDataGenerator = new CMSSignedDataGenerator();
    AlgorithmIdentifier sigAlgId = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withRSA");
    AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);
    AsymmetricKeyParameter privKeyParams = PrivateKeyFactory
            .createKey(this.authenticationPrivateKey.getEncoded());
    ContentSigner contentSigner = new BcRSAContentSignerBuilder(sigAlgId, digAlgId).build(privKeyParams);
    cmsSignedDataGenerator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .build(contentSigner, this.authenticationCertificate));
    if (includeCertificate) {
        cmsSignedDataGenerator/*  w w w  . j a  v  a 2  s  . c  o m*/
                .addCertificate(new X509CertificateHolder(this.authenticationCertificate.getEncoded()));
    }
    CMSTypedData cmsTypedData = new CMSProcessableByteArray(data);
    CMSSignedData cmsSignedData = cmsSignedDataGenerator.generate(cmsTypedData, true);
    return cmsSignedData.getEncoded();
}

From source file:be.fedict.eid.applet.service.signer.cms.AbstractCMSSignatureService.java

License:Open Source License

public DigestInfo preSign(List<DigestInfo> digestInfos, List<X509Certificate> signingCertificateChain,
        IdentityDTO identity, AddressDTO address, byte[] photo) throws NoSuchAlgorithmException {
    CMSSignedDataGenerator generator = createCMSSignedDataGenerator(signingCertificateChain);
    byte[] toBeSigned = getToBeSigned();
    CMSProcessable content = new CMSProcessableByteArray(toBeSigned);

    CMSProvider provider = new CMSProvider();
    SHA1WithRSAProxySignature.reset();/* www .j  a v  a2 s . c  om*/
    try {
        generator.generate(content, true, provider);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    }
    byte[] digestValue = SHA1WithRSAProxySignature.getDigestValue();
    String description = getSignatureDescription();
    DigestInfo digestInfo = new DigestInfo(digestValue, "SHA1", description);
    return digestInfo;
}

From source file:be.fedict.eid.applet.service.signer.cms.AbstractCMSSignatureService.java

License:Open Source License

public void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    CMSSignedDataGenerator generator;/*w ww .j  a v  a 2s . c o m*/
    try {
        generator = createCMSSignedDataGenerator(signingCertificateChain);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }

    byte[] toBeSigned = getToBeSigned();
    CMSProcessable content = new CMSProcessableByteArray(toBeSigned);

    CMSProvider provider = new CMSProvider();
    SHA1WithRSAProxySignature.reset();
    SHA1WithRSAProxySignature.setSignatureValue(signatureValue);
    CMSSignedData signedData;
    try {
        signedData = generator.generate(content, true, provider);
    } catch (CMSException e) {
        throw new RuntimeException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException(e);
    }
    byte[] cmsSignature;
    try {
        cmsSignature = signedData.getEncoded();
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
    this.storeCMSSignature(cmsSignature);
}

From source file:bluecrystal.bcdeps.helper.PkiOps.java

License:Open Source License

public boolean verify(String contentPath, String envPath) throws Exception {

    CMSSignedData csd = null;//ww w  . ja  va  2  s . c om
    byte[] buffer = loadEnv(envPath);
    if (contentPath != null) {
        byte[] content = getBytesFromFile(new File(contentPath));
        CMSProcessableByteArray cpbfile = new CMSProcessableByteArray(content);
        csd = new CMSSignedData(cpbfile, buffer);
    } else {
        csd = new CMSSignedData(buffer);
    }

    return verify(csd);

}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java

License:Open Source License

/**
 * A validao se basea apenas em assinaturas com um assinante apenas.
 * Valida apenas com o contedo do tipo DATA: OID ContentType
 * 1.2.840.113549.1.9.3 = OID Data 1.2.840.113549.1.7.1
 *
 * @param content/*from   w  ww .  j  ava2 s  . c  om*/
 * @param signed
 * @return
 * @params content Necessrio informar apenas se o pacote PKCS7 NO for do
 * tipo ATTACHED. Caso seja do tipo attached, este parmetro ser
 * substituido pelo contedo do pacote PKCS7.
 * @params signed Valor em bytes do pacote PKCS7, como por exemplo o
 * contedo de um arquivo ".p7s". No  a assinatura pura como no caso do
 * PKCS1. TODO: Implementar validao de co-assinaturas
 */
@Override
public boolean check(byte[] content, byte[] signed) {

    CMSSignedData signedData = null;
    PublicKey publicKey = null;

    try {
        if (content == null) {
            signedData = new CMSSignedData(signed);
        } else {
            signedData = new CMSSignedData(new CMSProcessableByteArray(content), signed);
        }
    } catch (CMSException exception) {
        throw new SignerException("Invalid bytes for a PKCS7 package", exception);
    }

    SignerInformationStore signerInformationStore = signedData.getSignerInfos();
    SignerInformation signerInformation = (SignerInformation) signerInformationStore.getSigners().iterator()
            .next();

    /*
     * Retirando o Certificado Digital e a chave Pblica da assinatura
     */
    try {
        CertStore certs;
        try {
            Security.addProvider(new BouncyCastleProvider());
            certs = signedData.getCertificatesAndCRLs("Collection", "BC");
            Collection<? extends Certificate> collCertificados = certs
                    .getCertificates(signerInformation.getSID());
            if (!collCertificados.isEmpty()) {
                certificate = (X509Certificate) collCertificados.iterator().next();
                publicKey = certificate.getPublicKey();
            }
        } catch (NoSuchAlgorithmException exception) {
            throw new SignerException(exception);
        } catch (NoSuchProviderException exception) {
            throw new SignerException(exception);
        } catch (CMSException exception) {
            throw new SignerException(exception);
        } catch (CertStoreException exception) {
            throw new SignerException(exception);
        }
    } catch (SignerException ex) {
        throw new SignerException(
                "Error on get information about certificates and public keys from a package PKCS7", ex);
    }

    try {
        signerInformation.verify(publicKey, "BC");
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException("Invalid signature", e);
    }

    AttributeTable signedAttributes = signerInformation.getSignedAttributes();

    if (signedAttributes == null) {
        throw new SignerException("Package PKCS7 without signed attributes");
    }

    // Validar a poltica
    org.bouncycastle.asn1.cms.Attribute signaturePolicyIdentifierAttribute = signedAttributes
            .get(new DERObjectIdentifier((new SignaturePolicyIdentifier()).getOID()));
    if (signaturePolicyIdentifierAttribute != null) {
        ASN1Set valueAttribute = signaturePolicyIdentifierAttribute.getAttrValues();
        for (Enumeration<DERSequence> iterator = valueAttribute.getObjects(); iterator.hasMoreElements();) {
            DERSequence sequence = iterator.nextElement();
            DERObjectIdentifier policyIdentifier = (DERObjectIdentifier) sequence.getObjectAt(0);
            String policyOID = policyIdentifier.getId();
            SignaturePolicy policy = SignaturePolicyFactory.getInstance().factory(policyOID);
            if (policy != null) {
                policy.validate(content, signed);
            } else {
                LOGGER.log(Level.WARNING, "N\u00e3o existe validador para a pol\u00edtica {0}", policyOID);
            }
        }
    } else {
        throw new SignerException("ICP-Brasil invalid format. There is not policy signature.");
    }
    return true;
}

From source file:br.gov.frameworkdemoiselle.certificate.signer.pkcs7.bc.CAdESSigner.java

License:Open Source License

/**
 * Mtodo de assinatura de dados e gerao do pacote PKCS7 Assina apenas com
 * o contedo do tipo DATA: OID ContentType 1.2.840.113549.1.9.3 = OID Data
 * 1.2.840.113549.1.7.1 Utiliza o algoritmo da propriedade algorithm. Caso
 * essa propriedade no esteja setada, o algoritmo do enum
 * {@link SignerAlgorithmEnum.DEFAULT} ser usado. Para este mtodo 
 * necessrio informar o contedo, a chave privada e um certificado digital
 * padro ICP-Brasil.//from   ww w  . j  a v a2s. c om
 *
 * @param content Contedo a ser assinado. TODO: Implementar co-assinaturas,
 * informar a poltica de assinatura
 * @return
 */
@Override
public byte[] signer(byte[] content) {
    Security.addProvider(new BouncyCastleProvider());

    if (this.certificate == null && this.certificateChain != null && this.certificateChain.length > 0) {
        this.certificate = (X509Certificate) this.certificateChain[0];
    }

    this.validateForSigner(content);

    if (this.certificateChain == null || this.certificateChain.length <= 1) {
        this.certificateChain = CAManager.getInstance().getCertificateChainArray(this.certificate);
    }

    //Adiciona o atributo de identificacao da politica
    SignaturePolicyIdentifier signaturePolicyIdentifier = new SignaturePolicyIdentifier();
    signaturePolicyIdentifier.setSignaturePolicyId(this.signaturePolicy.getSignaturePolicyId());
    this.addAttribute(signaturePolicyIdentifier);

    //Adiciona o astributo certificado de assinatura
    boolean addSigningCertificateAttribute = true;
    for (Attribute attribute : this.getAttributes()) {
        if (attribute instanceof SigningCertificate) {
            addSigningCertificateAttribute = false;
            break;
        }
    }
    if (addSigningCertificateAttribute) {
        SigningCertificate signingCertificateAttribute = this.signaturePolicy
                .getSigningCertificateAttribute(this.certificate);
        this.addAttribute(signingCertificateAttribute);
    }

    this.setCertificate((X509Certificate) certificateChain[0]);
    if (certificateChain.length == 1) {
        throw new SignerException("Impossivel extrair a cadeia de confianca do certificado");
    }

    String algorithmHashOID = null;
    String algorithmEncryptationOID = null;
    if (this.pkcs1 != null && this.pkcs1.getAlgorithm() != null
            && this.pkcs1.getAlgorithm().trim().length() > 0) {
        algorithmHashOID = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm()).getOIDAlgorithmHash();
        algorithmEncryptationOID = SignerAlgorithmEnum.valueOf(this.pkcs1.getAlgorithm())
                .getOIDAlgorithmCipher();
    } else {
        algorithmHashOID = this.signaturePolicy.getSignerAlgorithm().getOIDAlgorithmHash();
        algorithmEncryptationOID = this.signaturePolicy.getSignerAlgorithm().getOIDAlgorithmCipher();
    }

    byte[] result = null;

    CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator();
    try {
        signedDataGenerator.addCertificatesAndCRLs(this.generatedCertStore());
    } catch (CertStoreException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException(e);
    }

    // Valida o certificado usando a politica de certificacao
    this.signaturePolicy.validate(this.certificate, this.pkcs1.getPrivateKey());

    //Recupera o(s) certificado(s) de confianca para validacao
    Collection<X509Certificate> trustedCas = CAManager.getInstance()
            .getSignaturePolicyRootCAs(signaturePolicy.getSignaturePolicyId().getSigPolicyId());
    //Efetua a validacao das cadeias do certificado baseado na politica
    CAManager.getInstance().validateRootCAs(trustedCas, certificate);

    AttributeTable signedTable = this.mountSignedTable();
    AttributeTable unsignedTable = this.mountUnsignedTable();
    signedDataGenerator.addSigner(this.pkcs1.getPrivateKey(), this.certificate, algorithmEncryptationOID,
            algorithmHashOID, signedTable, unsignedTable);

    try {
        CMSProcessable processable = null;
        if (content == null) {
            processable = new CMSAbsentContent();
        } else {
            processable = new CMSProcessableByteArray(content);
        }
        CMSSignedData signedData = signedDataGenerator.generate(CMSSignedDataGenerator.DATA, processable,
                this.attached, this.getProviderName(), true);
        result = signedData.getEncoded();
    } catch (IOException e) {
        throw new SignerException(e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignerException(e);
    } catch (NoSuchProviderException e) {
        throw new SignerException(e);
    } catch (CMSException e) {
        throw new SignerException(e);
    }

    return result;
}