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:de.brendamour.jpasskit.signing.PKAbstractSIgningUtil.java

License:Apache License

protected byte[] signManifestUsingContent(PKSigningInformation signingInformation, CMSTypedData content)
        throws PKSigningException {
    if (signingInformation == null || !signingInformation.isValid()) {
        throw new IllegalArgumentException("Signing information not valid");
    }/*from   w ww . ja  v a 2s  .  c o  m*/

    try {
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
                .setProvider(BouncyCastleProvider.PROVIDER_NAME)
                .build(signingInformation.getSigningPrivateKey());

        final ASN1EncodableVector signedAttributes = new ASN1EncodableVector();
        final Attribute signingAttribute = new Attribute(CMSAttributes.signingTime,
                new DERSet(new DERUTCTime(new Date())));
        signedAttributes.add(signingAttribute);

        // Create the signing table
        final AttributeTable signedAttributesTable = new AttributeTable(signedAttributes);
        // Create the table table generator that will added to the Signer builder
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributesTable);

        generator.addSignerInfoGenerator(
                new JcaSignerInfoGeneratorBuilder(new JcaDigestCalculatorProviderBuilder()
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                                .setSignedAttributeGenerator(signedAttributeGenerator)
                                .build(sha1Signer, signingInformation.getSigningCert()));

        List<X509Certificate> certList = new ArrayList<X509Certificate>();
        certList.add(signingInformation.getAppleWWDRCACert());
        certList.add(signingInformation.getSigningCert());

        JcaCertStore certs = new JcaCertStore(certList);

        generator.addCertificates(certs);

        CMSSignedData sigData = generator.generate(content, false);
        return sigData.getEncoded();
    } catch (Exception e) {
        throw new PKSigningException("Error when signing manifest", e);
    }
}

From source file:de.brendamour.jpasskit.signing.PKSigningUtil.java

License:Apache License

public static void signManifestFile(final File temporaryPassDirectory, final File manifestJSONFile,
        final PKSigningInformation signingInformation) throws Exception {

    if (temporaryPassDirectory == null || manifestJSONFile == null || signingInformation == null
            || !signingInformation.isValid()) {
        throw new IllegalArgumentException("Null params are not supported");
    }/*from  w w  w . ja  v a 2s.  com*/
    addBCProvider();

    CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
    ContentSigner sha1Signer = new JcaContentSignerBuilder("SHA1withRSA")
            .setProvider(BouncyCastleProvider.PROVIDER_NAME).build(signingInformation.getSigningPrivateKey());

    generator.addSignerInfoGenerator(new JcaSignerInfoGeneratorBuilder(
            new JcaDigestCalculatorProviderBuilder().setProvider(BouncyCastleProvider.PROVIDER_NAME).build())
                    .build(sha1Signer, signingInformation.getSigningCert()));

    List<X509Certificate> certList = new ArrayList<X509Certificate>();
    certList.add(signingInformation.getAppleWWDRCACert());
    certList.add(signingInformation.getSigningCert());

    Store certs = new JcaCertStore(certList);

    generator.addCertificates(certs);

    CMSSignedData sigData = generator.generate(new CMSProcessableFile(manifestJSONFile), false);
    byte[] signedDataBytes = sigData.getEncoded();

    File signatureFile = new File(temporaryPassDirectory.getAbsolutePath() + File.separator + "signature");
    FileOutputStream signatureOutputStream = new FileOutputStream(signatureFile);
    signatureOutputStream.write(signedDataBytes);
    signatureOutputStream.close();
}

From source file:de.mendelson.util.security.BCCryptoHelper.java

/**
 * Create a pkcs7-signature of the passed content and returns it
 *
 * @param chain certificate chain, chain[0] is the signers certificate
 * itself//from  w  w  w.  jav a 2 s  .c om
 * @param embeddOriginalData Indicates if the original data should be
 * embedded in the signature
 *
 */
public byte[] sign(byte[] content, Certificate[] chain, Key key, String digest, boolean embeddOriginalData)
        throws Exception {
    X509Certificate x509Cert = this.castCertificate(chain[0]);
    PrivateKey privKey = this.getPrivateKey(key);
    CMSSignedDataGenerator signedDataGenerator = new CMSSignedDataGenerator();
    //add dont know
    ASN1EncodableVector signedAttrs = new ASN1EncodableVector();
    SMIMECapabilityVector caps = new SMIMECapabilityVector();
    caps.addCapability(SMIMECapability.dES_EDE3_CBC);
    caps.addCapability(SMIMECapability.rC2_CBC, 128);
    caps.addCapability(SMIMECapability.dES_CBC);
    signedAttrs.add(new SMIMECapabilitiesAttribute(caps));
    if (digest.equalsIgnoreCase(ALGORITHM_SHA1)) {
        signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA1withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_MD5)) {
        signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("MD5withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA224)) {
        signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA224withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA256)) {
        signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA256withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA384)) {
        signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA384withRSA", privKey, x509Cert));
    } else if (digest.equalsIgnoreCase(ALGORITHM_SHA512)) {
        signedDataGenerator.addSignerInfoGenerator(new JcaSimpleSignerInfoGeneratorBuilder().setProvider("BC")
                .setSignedAttributeGenerator(new AttributeTable(signedAttrs))
                .build("SHA512withRSA", privKey, x509Cert));
    } else {
        throw new Exception("sign: Signing digest " + digest + " not supported.");
    }
    //add cert store
    List<Certificate> certList = Arrays.asList(chain);
    Store certStore = new JcaCertStore(certList);
    signedDataGenerator.addCertificates(certStore);
    if (content == null) {
        throw new Exception("sign: content is absent");
    }
    CMSTypedData processable = new CMSProcessableByteArray(content);
    CMSSignedData signatureData = signedDataGenerator.generate(processable, embeddOriginalData);
    return (signatureData.getEncoded());
}

From source file:dorkbox.util.crypto.CryptoX509.java

License:Apache License

/**
 * Creates a NEW signature block that contains the pkcs7 (minus content, which is the .SF file)
 * signature of the .SF file./*ww  w .ja  v a  2s . c  o m*/
 *
 * It contains the hash of the data, and the verification signature.
 */
public static byte[] createSignature(byte[] signatureSourceData, X509CertificateHolder x509CertificateHolder,
        AsymmetricKeyParameter privateKey) {

    try {
        CMSTypedData content = new CMSProcessableByteArray(signatureSourceData);

        ASN1ObjectIdentifier contentTypeOID = new ASN1ObjectIdentifier(content.getContentType().getId());
        ASN1EncodableVector digestAlgs = new ASN1EncodableVector();
        ASN1EncodableVector signerInfos = new ASN1EncodableVector();

        AlgorithmIdentifier sigAlgId = x509CertificateHolder.getSignatureAlgorithm();
        AlgorithmIdentifier digAlgId = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlgId);

        // use the bouncy-castle lightweight API to generate a hash of the signature source data (usually the signature file bytes)
        BcContentSignerBuilder contentSignerBuilder;
        AlgorithmIdentifier digEncryptionAlgorithm;

        if (privateKey instanceof ECPrivateKeyParameters) {
            contentSignerBuilder = new BcECDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof DSAPrivateKeyParameters) {
            contentSignerBuilder = new BcDSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(DSAUtil.dsaOids[0], null); // 1.2.840.10040.4.1  // DSA hashID
        } else if (privateKey instanceof RSAPrivateCrtKeyParameters) {
            contentSignerBuilder = new BcRSAContentSignerBuilder(sigAlgId, digAlgId);
            digEncryptionAlgorithm = new AlgorithmIdentifier(RSAUtil.rsaOids[0], null); // 1.2.840.113549.1.1.1 // RSA hashID
        } else {
            throw new RuntimeException("Invalid signature type. Only ECDSA, DSA, RSA supported.");
        }

        ContentSigner hashSigner = contentSignerBuilder.build(privateKey);
        OutputStream outputStream = hashSigner.getOutputStream();
        outputStream.write(signatureSourceData, 0, signatureSourceData.length);
        outputStream.flush();
        byte[] sigBytes = hashSigner.getSignature();

        SignerIdentifier sigId = new SignerIdentifier(
                new IssuerAndSerialNumber(x509CertificateHolder.toASN1Structure()));

        SignerInfo inf = new SignerInfo(sigId, digAlgId, null, digEncryptionAlgorithm,
                new DEROctetString(sigBytes), (ASN1Set) null);

        digestAlgs.add(inf.getDigestAlgorithm());
        signerInfos.add(inf);

        ASN1EncodableVector certs = new ASN1EncodableVector();
        certs.add(x509CertificateHolder.toASN1Structure());

        ContentInfo encInfo = new ContentInfo(contentTypeOID, null);
        SignedData sd = new SignedData(new DERSet(digestAlgs), encInfo, new BERSet(certs), null,
                new DERSet(signerInfos));

        ContentInfo contentInfo = new ContentInfo(CMSObjectIdentifiers.signedData, sd);
        CMSSignedData cmsSignedData2 = new CMSSignedData(content, contentInfo);

        return cmsSignedData2.getEncoded();
    } catch (Throwable t) {
        logger.error("Error signing data.", t);
        throw new RuntimeException("Error trying to sign data. " + t.getMessage());
    }
}

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

License:Open Source License

public byte[] sign(byte[] data, PrivateKey privateKey, Certificate[] chain) {
    X509Certificate cert = (X509Certificate) chain[0];
    try {/*  w w w  .j av a2 s  . c  o  m*/
        CMSSignedDataGenerator generator = new CMSSignedDataGenerator();
        generator.addSigner(privateKey, cert, CMSSignedDataGenerator.DIGEST_SHA1);

        CertStore certsAndCRLS = CertStore.getInstance("Collection",
                new CollectionCertStoreParameters(Arrays.asList(chain)));
        generator.addCertificatesAndCRLs(certsAndCRLS);

        CMSProcessable content = new CMSProcessableByteArray(data);
        CMSSignedData signedData = generator.generate(content, true, keyStore.getProvider().getName());

        return signedData.getEncoded();
    } catch (GeneralSecurityException e) {
        throw new RuntimeException(e); // FIXME

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

    } catch (IOException 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 {//  w w w  . j ava 2  s . c  o 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:edu.utn.frba.grupo5303.serverenviolibre.services.WSAfipService.java

private byte[] create_cms(String p12file, String p12pass, String signer, String dstDN, String service,
        Long TicketTime) {//from   ww  w.jav a  2  s. c o  m

    PrivateKey pKey = null;
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;
    String LoginTicketRequest_xml;
    String SignerDN = null;

    ArrayList<X509Certificate> certList = null;

    //
    // Manage Keys & Certificates
    //
    try {
        // Create a keystore using keys from the pkcs#12 p12file
        KeyStore ks = KeyStore.getInstance("pkcs12");
        InputStream p12stream = getClass().getResourceAsStream(p12file);
        ks.load(p12stream, p12pass.toCharArray());
        p12stream.close();

        // Get Certificate & Private key from KeyStore
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);
        SignerDN = pCertificate.getSubjectDN().toString();

        // Create a list of Certificates to include in the final CMS
        certList = new ArrayList<X509Certificate>();
        certList.add(pCertificate);

        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (Exception e) {
        logger.log(Level.SEVERE, "---### Exception ###---: {0}", e);
    }

    //
    // Create XML Message
    // 
    LoginTicketRequest_xml = create_LoginTicketRequest(SignerDN, dstDN, service, TicketTime);

    //
    // Create CMS Message
    //
    try {
        // Create a new empty CMS Message
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

        // Add a Signer to the Message
        gen.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);

        // Add the Certificate to the Message
        gen.addCertificatesAndCRLs(cstore);

        // Add the data (XML) to the Message
        CMSProcessable data = new CMSProcessableByteArray(LoginTicketRequest_xml.getBytes());

        // Add a Sign of the Data to the Message
        CMSSignedData signed = gen.generate(data, true, "BC");

        asn1_cms = signed.getEncoded();

    } catch (Exception e) {
        logger.log(Level.SEVERE, "---### Exception ###---: {0}", e);
    }

    return (asn1_cms);
}

From source file:edu.utn.frba.grupo5303.wsaacliente.Facturador.java

public String solicitarFECAE() throws CertStoreException, CMSException, NoSuchAlgorithmException,
        NoSuchProviderException, IOException, ServiceException {
    PrivateKey pKey = null;/*from   w  ww .  ja va  2s  .  com*/
    X509Certificate pCertificate = null;
    byte[] asn1_cms = null;
    CertStore cstore = null;

    ArrayList<X509Certificate> certList = null;

    //
    // Manage Keys & Certificates
    //
    try {
        // Create a keystore using keys from the pkcs#12 p12file
        KeyStore ks = KeyStore.getInstance("pkcs12");
        FileInputStream p12stream = new FileInputStream(p12file);
        ks.load(p12stream, p12pass.toCharArray());
        p12stream.close();

        // Get Certificate & Private key from KeyStore
        pKey = (PrivateKey) ks.getKey(signer, p12pass.toCharArray());
        pCertificate = (X509Certificate) ks.getCertificate(signer);

        // Create a list of Certificates to include in the final CMS
        certList = new ArrayList<X509Certificate>();
        certList.add(pCertificate);

        if (Security.getProvider("BC") == null) {
            Security.addProvider(new BouncyCastleProvider());
        }

        cstore = CertStore.getInstance("Collection", new CollectionCertStoreParameters(certList), "BC");
    } catch (Exception e) {
        e.printStackTrace();
    }

    String pedido = generarXMLPedido();

    // Create a new empty CMS Message
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    // Add a Signer to the Message
    gen.addSigner(pKey, pCertificate, CMSSignedDataGenerator.DIGEST_SHA1);

    // Add the Certificate to the Message
    gen.addCertificatesAndCRLs(cstore);

    // Add the data (XML) to the Message
    CMSProcessable data = new CMSProcessableByteArray(pedido.getBytes());

    //        FECAESolicitar sol = new FECAESolicitar();
    //        sol.setAuth(new FEAuthRequest());
    //        sol.setFeCAEReq(new FECAERequest());        

    // Add a Sign of the Data to the Message
    CMSSignedData signed = gen.generate(data, true, "BC");

    // 
    asn1_cms = signed.getEncoded();

    Service service = new Service();
    Call call = (Call) service.createCall();

    //
    // Prepare the call for the Web service
    //
    call.setTargetEndpointAddress(new java.net.URL("https://wswhomo.afip.gov.ar/wsfev1/service.asmx"));
    call.setOperationName("FECAESolicitar");
    call.addParameter("request", XMLType.XSD_STRING, ParameterMode.IN);
    call.setReturnType(XMLType.XSD_STRING);

    //
    // Make the actual call and assign the answer to a String
    //
    String response = (String) call.invoke(new Object[] { Base64.encode(asn1_cms) });

    return response;
}

From source file:es.mityc.firmaJava.libreria.pkcs7.FirmaPkcs7.java

License:LGPL

public static byte[] firmar(Frame padre, X509Certificate cert, byte[] datos) throws KeyStoreException,
        NoSuchAlgorithmException, UnrecoverableKeyException, InvalidAlgorithmParameterException,
        NoSuchProviderException, CertStoreException, CMSException, IOException {
    byte[] bytesFirma = null;

    // Valida la tarjeta criptogrfica

    ValidaTarjeta vt = new ValidaTarjeta(padre);
    vt.setVisible(true);/*ww  w .  j  a v a  2  s  .com*/
    // Esperamos mientras se valida la tarjeta...
    vt.setVisible(false);

    // Genera la firma PKCS#7

    PrivateKey privateKey = vt.getPrivateKey(cert);

    CMSProcessable msg = new CMSProcessableByteArray(datos);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    gen.addSigner(privateKey, cert, CMSSignedDataGenerator.DIGEST_SHA1);

    KeyStore ks = vt.getKeyStore();
    String alias = vt.getAlias(cert);

    Certificate[] certChain = ks.getCertificateChain(alias);

    CertStore certs = CertStore.getInstance(COLLECTION,
            new CollectionCertStoreParameters(Arrays.asList(certChain)), BC);
    gen.addCertificatesAndCRLs(certs);

    CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, true, SUNPCKS11_TOKEN, true);
    bytesFirma = s.getEncoded();
    return bytesFirma;
}

From source file:es.mityc.firmaJava.libreria.pkcs7.FirmaPkcs7.java

License:LGPL

public static byte[] firmar(ValidaTarjeta vt, X509Certificate cert, byte[] datos) throws KeyStoreException,
        NoSuchAlgorithmException, UnrecoverableKeyException, InvalidAlgorithmParameterException,
        NoSuchProviderException, CertStoreException, CMSException, IOException {
    byte[] bytesFirma = null;

    PrivateKey privateKey = vt.getPrivateKey(cert);

    CMSProcessable msg = new CMSProcessableByteArray(datos);
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
    gen.addSigner(privateKey, cert, CMSSignedDataGenerator.DIGEST_SHA1);

    KeyStore ks = vt.getKeyStore();
    String alias = vt.getAlias(cert);

    Certificate[] certChain = ks.getCertificateChain(alias);

    CertStore certs = CertStore.getInstance(COLLECTION,
            new CollectionCertStoreParameters(Arrays.asList(certChain)), BC);
    gen.addCertificatesAndCRLs(certs);/*w  w  w.ja  v a2s .co  m*/

    CMSSignedData s = gen.generate(CMSSignedDataGenerator.DATA, msg, true, SUNPCKS11_TOKEN, true);
    bytesFirma = s.getEncoded();
    return bytesFirma;
}