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: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:CreateSignatureBase.java

License:Apache License

/**
 * SignatureInterface implementation.// w w w. j  av a2  s  .  c o 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. <-- TODO this method should be private
 *
 * Use your favorite cryptographic library to implement PKCS #7 signature creation.
 */
@Override
public byte[] sign(InputStream content) throws IOException {
    try {
        List<Certificate> certList = new ArrayList<Certificate>();
        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 e) {
        throw new IOException(e);
    } catch (CMSException e) {
        throw new IOException(e);
    } catch (TSPException e) {
        throw new IOException(e);
    } catch (OperatorCreationException e) {
        throw new IOException(e);
    }
}

From source file:createSod.java

License:Open Source License

/**
 * @param args//from   w  w  w . jav a 2  s.c om
 * @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 {/*  w  w  w .  j a  va2 s  .c o m*/
        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[] 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//from   w  w w . ja  v  a2 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 void postSign(byte[] signatureValue, List<X509Certificate> signingCertificateChain) {
    CMSSignedDataGenerator generator;/*  ww  w  . ja v a2s  .com*/
    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: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.//w  w w.j a  va2s  .c  o m
 *
 * @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;
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("static-access")
protected static byte[] converterPkcs7EmCMSComCertificadosECRLs(final byte[] assinatura) throws Exception {
    CMSSignedData cmssd = new CMSSignedData(assinatura);

    Store certs = cmssd.getCertificates();
    Store certsAndCrls = buscarCrlParaCadaCertificado(certs);
    CMSSignedData cmssdcrl = cmssd.replaceCertificatesAndCRLs(cmssd, certsAndCrls, certsAndCrls, certsAndCrls);

    return cmssdcrl.getEncoded();
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static void main(String[] args) throws Exception {
    byte[] pdf;//from w  w  w  .j a va2 s  . c o  m
    {
        File f = new File("c:/trabalhos/java/teste.pdf");
        FileInputStream fin = new FileInputStream(f);
        pdf = new byte[(int) f.length()];
        fin.read(pdf);
        fin.close();
    }

    PdfReader reader = new PdfReader(pdf);
    FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf");

    final int SIZE = 256000;

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.setSignDate(Calendar.getInstance());
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());
    FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64");
    fout2.write(Base64.encode(data).getBytes());
    fout2.close();
    File f = new File("c:/trabalhos/java/teste_sign.b64");
    FileInputStream fin = new FileInputStream(f);
    byte[] signatureB64 = new byte[(int) f.length()];
    fin.read(signatureB64);
    @SuppressWarnings("unused")
    StringBuilder sb = new StringBuilder();
    byte[] signature1 = Base64.decode(new String(signatureB64));
    fin.close();
    byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1);
    CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP));
    // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura);
    byte[] signature = A_T.getEncoded();

    byte[] outc = new byte[(SIZE - 2) / 2];
    System.arraycopy(signature, 0, outc, 0, signature.length);
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
}

From source file:br.gov.jfrj.siga.cd.AssinaturaDigital.java

License:Open Source License

@SuppressWarnings("unchecked")
protected static void addSignatureToPDF(byte[] pdf, byte[] signature) throws Exception {
    PdfReader reader = new PdfReader(pdf);
    FileOutputStream fout = new FileOutputStream("c:/trabalhos/java/teste_assinado.pdf");

    final int SIZE = 128000;

    PdfStamper stp = PdfStamper.createSignature(reader, fout, '\0');
    PdfSignatureAppearance sap = stp.getSignatureAppearance();

    PdfDictionary dic = new PdfDictionary();
    dic.put(PdfName.TYPE, PdfName.SIG);//from  w  ww  .  j  av  a 2  s  . co  m
    dic.put(PdfName.FILTER, new PdfName("Adobe.PPKMS"));
    dic.put(PdfName.SUBFILTER, new PdfName("adbe.pkcs7.detached"));

    sap.setCryptoDictionary(dic);
    HashMap exc = new HashMap();
    exc.put(PdfName.CONTENTS, new Integer(SIZE));
    sap.preClose(exc);

    byte[] data = streamToByteArray(sap.getRangeStream());
    FileOutputStream fout2 = new FileOutputStream("c:/trabalhos/java/teste_hash.b64");
    fout2.write(Base64.encode(data).getBytes());
    fout2.close();
    File f = new File("c:/trabalhos/java/teste_sign.b64");
    FileInputStream fin = new FileInputStream(f);
    byte[] signatureB64 = new byte[(int) f.length()];
    fin.read(signatureB64);
    @SuppressWarnings("unused")
    StringBuilder sb = new StringBuilder();
    byte[] signature1 = Base64.decode(new String(signatureB64));
    fin.close();
    byte[] A_CP = converterPkcs7EmCMSComCertificadosECRLs(signature1);
    CMSSignedData A_T = TimeStamper.addTimestamp(new CMSSignedData(A_CP));
    // verificarAssinaturaCMS(conteudo, A_T.getEncoded(), dtAssinatura);
    signature = A_T.getEncoded();

    byte[] outc = new byte[(SIZE - 2) / 2];
    System.arraycopy(signature, 0, outc, 0, signature.length);
    PdfDictionary dic2 = new PdfDictionary();

    dic2.put(PdfName.CONTENTS, new PdfString(outc).setHexWriting(true));
    sap.close(dic2);
}