Example usage for org.bouncycastle.cms DefaultSignedAttributeTableGenerator DefaultSignedAttributeTableGenerator

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

Introduction

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

Prototype

public DefaultSignedAttributeTableGenerator(AttributeTable attributeTable) 

Source Link

Document

Initialise with some extra attributes or overrides.

Usage

From source file:com.zotoh.crypto.CryptoUte.java

License:Open Source License

private static SMIMESignedGenerator makeSignerGentor(PrivateKey key, Certificate[] certs, SigningAlgo algo)
        throws CertStoreException, NoSuchAlgorithmException, InvalidAlgorithmParameterException,
        GeneralSecurityException, CertificateEncodingException {

    SMIMESignedGenerator gen = new SMIMESignedGenerator("base64");
    List<Certificate> lst = asList(true, certs);

    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));

    X509Certificate x0 = (X509Certificate) certs[0];
    X509Certificate issuer = x0;//from   ww w  . java 2  s  .co  m
    X500Principal issuerDN;

    if (certs.length > 1) {
        issuer = (X509Certificate) certs[1];
    }

    issuerDN = issuer.getSubjectX500Principal();
    x0 = (X509Certificate) certs[0];

    //
    // add an encryption key preference for encrypted responses -
    // normally this would be different from the signing certificate...
    //

    IssuerAndSerialNumber issAndSer = new IssuerAndSerialNumber(X500Name.getInstance(issuerDN.getEncoded()),
            x0.getSerialNumber());
    Provider prov = Crypto.getInstance().getProvider();

    signedAttrs.add(new SMIMEEncryptionKeyPreferenceAttribute(issAndSer));

    try {
        JcaSignerInfoGeneratorBuilder bdr = new JcaSignerInfoGeneratorBuilder(
                new JcaDigestCalculatorProviderBuilder().setProvider(prov).build());
        bdr.setDirectSignature(true);

        ContentSigner cs = new JcaContentSignerBuilder(algo.toString()).setProvider(prov).build(key);

        bdr.setSignedAttributeGenerator(
                new DefaultSignedAttributeTableGenerator(new AttributeTable(signedAttrs)));

        gen.addSignerInfoGenerator(bdr.build(cs, x0));
        gen.addCertificates(new JcaCertStore(lst));

        return gen;
    } catch (OperatorCreationException e) {
        throw new GeneralSecurityException(e);
    }
}

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");
    }/*w w  w. ja  v a2  s  .  co 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:eu.betaas.service.securitymanager.capability.utils.CapabilityUtils.java

License:Apache License

/**
 * Method to create exCap's signature with the issuer certificate detached 
 * from the signed data /*from  w  w  w  . j av  a2  s .c  o  m*/
 * @param credentials: the credential that contains private key to sign the
 * data
 * @param content: the data or content to be signed
 * @return: signed data in byte[]
 * @throws OperatorCreationException
 * @throws CMSException
 * @throws IOException
 */
public static byte[] createCapSignature(BcCredential credentials, String content)
        throws OperatorCreationException, CMSException, IOException {

    AsymmetricKeyParameter key = credentials.getPrivateKey();
    X509CertificateHolder[] chain = credentials.getCertificateChain();

    X509CertificateHolder cert = chain[0];
    //    Store certs = new CollectionStore(Arrays.asList(chain));

    // construct SignerInfoGenerator manually --> to deal with signingTime issue
    SignerInfoGeneratorBuilder sigBuilder = new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider());

    Hashtable<ASN1ObjectIdentifier, Attribute> signedAttr = new Hashtable<ASN1ObjectIdentifier, Attribute>();

    Attribute attr = new Attribute(CMSAttributes.signingTime, new DERSet(new Time(new java.util.Date())));

    signedAttr.put(attr.getAttrType(), attr);
    AttributeTable signedAttributeTable = new AttributeTable(signedAttr);

    sigBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttributeTable));

    // set up the generator
    CMSSignedDataGenerator gen = new CMSSignedDataGenerator();

    AlgorithmIdentifier sigAlg = new DefaultSignatureAlgorithmIdentifierFinder().find("SHA1withECDSA");
    AlgorithmIdentifier digAlg = new DefaultDigestAlgorithmIdentifierFinder().find(sigAlg);

    SignerInfoGenerator signerInfoGen = sigBuilder
            .build(new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(key), cert);

    gen.addSignerInfoGenerator(signerInfoGen);

    //    gen.addSignerInfoGenerator(new SignerInfoGeneratorBuilder(new BcDigestCalculatorProvider()).build(new BcECDSAContentSignerBuilder(sigAlg, digAlg).build(key), cert));
    // do not store the certificate with signed data (i.e. detached signature)
    //    gen.addCertificates(certs);

    // create the signed-data object
    CMSTypedData data = new CMSProcessableByteArray(content.getBytes());

    CMSSignedData signed = gen.generate(data);

    // recreate
    //    signed = new CMSSignedData(data, signed.getEncoded());

    return signed.getEncoded();
}

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

License:Open Source License

/**
 * @param signedAttributes   the signedAttributes
 * @param unsignedAttributes the unsignedAttributes
 * @return a SignerInfoGeneratorBuilder that generate the signed and unsigned attributes according to the parameters
 *///from  w  ww.  ja v a2s  .  c om
private SignerInfoGeneratorBuilder getSignerInfoGeneratorBuilder(AttributeTable signedAttributes,
        AttributeTable unsignedAttributes) {

    if (signedAttributes != null && signedAttributes.size() == 0) {
        signedAttributes = null;
    }
    final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
            signedAttributes);
    if (unsignedAttributes != null && unsignedAttributes.size() == 0) {
        unsignedAttributes = null;
    }
    final SimpleAttributeTableGenerator unsignedAttributeGenerator = new SimpleAttributeTableGenerator(
            unsignedAttributes);

    return getSignerInfoGeneratorBuilder(signedAttributeGenerator, unsignedAttributeGenerator);
}

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

License:Open Source License

/**
 * @param signedAttributes   the signedAttributes
 * @param unsignedAttributes the unsignedAttributes
 * @return a SignerInfoGeneratorBuilder that generate the signed and unsigned attributes according to the parameters
 *//*from  ww  w .  j  av a  2  s .co  m*/
private SignerInfoGeneratorBuilder getSignerInfoGeneratorBuilder(AttributeTable signedAttributes,
        AttributeTable unsignedAttributes) {

    if ((signedAttributes != null) && (signedAttributes.size() == 0)) {
        signedAttributes = null;
    }
    final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
            signedAttributes);
    if ((unsignedAttributes != null) && (unsignedAttributes.size() == 0)) {
        unsignedAttributes = null;
    }
    final SimpleAttributeTableGenerator unsignedAttributeGenerator = new SimpleAttributeTableGenerator(
            unsignedAttributes);

    return getSignerInfoGeneratorBuilder(signedAttributeGenerator, unsignedAttributeGenerator);
}

From source file:eu.europa.esig.dss.cookbook.mock.MockTSPSource.java

License:Open Source License

@Override
public TimeStampToken getTimeStampResponse(final DigestAlgorithm digestAlgorithm, final byte[] digest)
        throws DSSException {

    final String signatureAlgorithm = getSignatureAlgorithm(digestAlgorithm, digest);

    final TimeStampRequestGenerator tsqGenerator = new TimeStampRequestGenerator();
    tsqGenerator.setCertReq(true);/*  w  ww  . ja va 2 s . co  m*/

    /**
     * The code below guarantee that the dates of the two successive
     * timestamps are different. This is activated only if timestampDate is provided at
     * construction time
     */
    Date timestampDate_ = new Date();

    if (policyOid != null) {
        tsqGenerator.setReqPolicy(policyOid);
    }

    TimeStampRequest tsRequest = null;
    if (useNonce) {
        final BigInteger nonce = BigInteger.valueOf(random.nextLong());
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest, nonce);
    } else {
        tsRequest = tsqGenerator.generate(new ASN1ObjectIdentifier(digestAlgorithm.getOid()), digest);
    }

    try {
        final ContentSigner sigGen = new JcaContentSignerBuilder(signatureAlgorithm).build(key);
        final JcaX509CertificateHolder certHolder = new JcaX509CertificateHolder(cert.getCertificate());

        // that to make sure we generate the same timestamp data for the
        // same timestamp date
        AttributeTable signedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        signedAttributes = signedAttributes.add(PKCSObjectIdentifiers.pkcs_9_at_signingTime,
                new Time(timestampDate_));
        final DefaultSignedAttributeTableGenerator signedAttributeGenerator = new DefaultSignedAttributeTableGenerator(
                signedAttributes);
        AttributeTable unsignedAttributes = new AttributeTable(new Hashtable<ASN1ObjectIdentifier, Object>());
        final SimpleAttributeTableGenerator unsignedAttributeGenerator = new SimpleAttributeTableGenerator(
                unsignedAttributes);

        final DigestCalculatorProvider digestCalculatorProvider = new BcDigestCalculatorProvider();
        SignerInfoGeneratorBuilder sigInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
                digestCalculatorProvider);
        sigInfoGeneratorBuilder.setSignedAttributeGenerator(signedAttributeGenerator);
        sigInfoGeneratorBuilder.setUnsignedAttributeGenerator(unsignedAttributeGenerator);
        final SignerInfoGenerator sig = sigInfoGeneratorBuilder.build(sigGen, certHolder);

        final DigestCalculator sha1DigestCalculator = DSSRevocationUtils.getSHA1DigestCalculator();

        final TimeStampTokenGenerator tokenGenerator = new TimeStampTokenGenerator(sig, sha1DigestCalculator,
                policyOid);
        final Set<X509Certificate> singleton = new HashSet<X509Certificate>();
        singleton.add(cert.getCertificate());
        tokenGenerator.addCertificates(new JcaCertStore(singleton));
        final TimeStampResponseGenerator generator = new TimeStampResponseGenerator(tokenGenerator,
                TSPAlgorithms.ALLOWED);

        Date responseDate = new Date();
        TimeStampResponse tsResponse = generator.generate(tsRequest, BigInteger.ONE, responseDate);
        final TimeStampToken timeStampToken = tsResponse.getTimeStampToken();
        return timeStampToken;
    } catch (OperatorCreationException e) {
        throw new DSSException(e);
    } catch (CertificateEncodingException e) {
        throw new DSSException(e);
    } catch (TSPException e) {
        throw new DSSException(e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImpl.java

License:Open Source License

private void addSigner(PrivateKey privateKey, X509Certificate signer, SMIMESigningAlgorithm algorithm,
        AttributeTable signedAttr, AttributeTable unsignedAttr) throws SMIMEBuilderException {
    try {//from   w  ww.  j a  va 2  s.  c om
        JcaDigestCalculatorProviderBuilder digestBuilder = new JcaDigestCalculatorProviderBuilder();

        digestBuilder.setProvider(nonSensitiveProvider);

        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(digestBuilder.build());

        if (signedAttr != null) {
            signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr));
        }

        if (unsignedAttr != null) {
            signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr));
        }

        JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(algorithm.getAlgorithm());

        contentSignerBuilder.setProvider(sensitiveProvider);

        SignerInfoGenerator signerInfoGenerator = signerInfoBuilder
                .build(contentSignerBuilder.build(privateKey), new JcaX509CertificateHolder(signer));

        signedGenerator.addSignerInfoGenerator(signerInfoGenerator);
    } catch (OperatorCreationException e) {
        throw new SMIMEBuilderException(e);
    } catch (CertificateEncodingException e) {
        throw new SMIMEBuilderException(e);
    }
}

From source file:mitm.common.security.smime.SMIMEBuilderImpl.java

License:Open Source License

public void addSigner(PrivateKey privateKey, byte[] subjectKeyIdentifier, SMIMESigningAlgorithm algorithm,
        AttributeTable signedAttr, AttributeTable unsignedAttr) throws SMIMEBuilderException {
    try {//  ww  w  .  ja  v  a2  s . c  o  m
        JcaDigestCalculatorProviderBuilder digestBuilder = new JcaDigestCalculatorProviderBuilder();

        digestBuilder.setProvider(nonSensitiveProvider);

        SignerInfoGeneratorBuilder signerInfoBuilder = new SignerInfoGeneratorBuilder(digestBuilder.build());

        if (signedAttr != null) {
            signerInfoBuilder.setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(signedAttr));
        }

        if (unsignedAttr != null) {
            signerInfoBuilder.setUnsignedAttributeGenerator(new SimpleAttributeTableGenerator(unsignedAttr));
        }

        JcaContentSignerBuilder contentSignerBuilder = new JcaContentSignerBuilder(algorithm.getAlgorithm());

        contentSignerBuilder.setProvider(sensitiveProvider);

        SignerInfoGenerator signerInfoGenerator = signerInfoBuilder
                .build(contentSignerBuilder.build(privateKey), subjectKeyIdentifier);

        signedGenerator.addSignerInfoGenerator(signerInfoGenerator);
    } catch (OperatorCreationException e) {
        throw new SMIMEBuilderException(e);
    }
}

From source file:net.jsign.PESigner.java

License:Apache License

private CMSSignedData createSignature(PEFile file)
        throws IOException, CMSException, OperatorCreationException, CertificateEncodingException {
    byte[] sha = file.computeDigest(algo);

    AlgorithmIdentifier algorithmIdentifier = new AlgorithmIdentifier(algo.oid, DERNull.INSTANCE);
    DigestInfo digestInfo = new DigestInfo(algorithmIdentifier, sha);
    SpcAttributeTypeAndOptionalValue data = new SpcAttributeTypeAndOptionalValue(
            AuthenticodeObjectIdentifiers.SPC_PE_IMAGE_DATA_OBJID, new SpcPeImageData());
    SpcIndirectDataContent spcIndirectDataContent = new SpcIndirectDataContent(data, digestInfo);

    ContentSigner shaSigner = new JcaContentSignerBuilder(algo + "with" + privateKey.getAlgorithm())
            .build(privateKey);/*from w w  w.j  av a  2  s  . c  o  m*/
    DigestCalculatorProvider digestCalculatorProvider = new JcaDigestCalculatorProviderBuilder().build();

    // prepare the authenticated attributes
    CMSAttributeTableGenerator attributeTableGenerator = new DefaultSignedAttributeTableGenerator(
            createAuthenticatedAttributes());

    // fetch the signing certificate
    X509CertificateHolder certificate = new JcaX509CertificateHolder((X509Certificate) chain[0]);

    // prepare the signerInfo with the extra authenticated attributes
    SignerInfoGeneratorBuilder signerInfoGeneratorBuilder = new SignerInfoGeneratorBuilder(
            digestCalculatorProvider);
    signerInfoGeneratorBuilder.setSignedAttributeGenerator(attributeTableGenerator);
    SignerInfoGenerator signerInfoGenerator = signerInfoGeneratorBuilder.build(shaSigner, certificate);

    AuthenticodeSignedDataGenerator generator = new AuthenticodeSignedDataGenerator();
    generator.addCertificates(new JcaCertStore(removeRoot(chain)));
    generator.addSignerInfoGenerator(signerInfoGenerator);

    return generator.generate(AuthenticodeObjectIdentifiers.SPC_INDIRECT_DATA_OBJID, spcIndirectDataContent);
}

From source file:net.ripe.rpki.commons.crypto.cms.RpkiSignedObjectBuilder.java

License:BSD License

private void addSignerInfo(CMSSignedDataGenerator generator, PrivateKey privateKey, String signatureProvider,
        X509Certificate signingCertificate) throws OperatorCreationException {
    ContentSigner signer = new JcaContentSignerBuilder(X509CertificateBuilderHelper.DEFAULT_SIGNATURE_ALGORITHM)
            .setProvider(signatureProvider).build(privateKey);
    DigestCalculatorProvider digestProvider = BouncyCastleUtil.DIGEST_CALCULATOR_PROVIDER;
    SignerInfoGenerator gen = new JcaSignerInfoGeneratorBuilder(digestProvider)
            .setSignedAttributeGenerator(new DefaultSignedAttributeTableGenerator(
                    createSignedAttributes(signingCertificate.getNotBefore())))
            .build(signer, X509CertificateUtil.getSubjectKeyIdentifier(signingCertificate));
    generator.addSignerInfoGenerator(gen);
}