Example usage for org.bouncycastle.util CollectionStore CollectionStore

List of usage examples for org.bouncycastle.util CollectionStore CollectionStore

Introduction

In this page you can find the example usage for org.bouncycastle.util CollectionStore CollectionStore.

Prototype

public CollectionStore(Collection collection) 

Source Link

Document

Basic constructor.

Usage

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

License:Open Source License

protected CMSSignedData postExtendCMSSignedData(CMSSignedData cmsSignedData,
        SignerInformation signerInformation, SignatureParameters parameters) {
    CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
    cadesSignature.setDetachedContents(parameters.getDetachedContent());
    final ValidationContext validationContext = cadesSignature
            .getSignatureValidationContext(certificateVerifier);

    Store certificatesStore = cmsSignedData.getCertificates();
    final Store attributeCertificatesStore = cmsSignedData.getAttributeCertificates();
    Store crlsStore = cmsSignedData.getCRLs();
    Store otherRevocationInfoFormatStoreBasic = cmsSignedData
            .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
    Store otherRevocationInfoFormatStoreOcsp = cmsSignedData
            .getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);

    final Set<CertificateToken> certificates = cadesSignature.getCertificatesForInclusion(validationContext);
    final Collection<X509CertificateHolder> newCertificateStore = new HashSet<X509CertificateHolder>(
            certificatesStore.getMatches(null));
    for (final CertificateToken certificateToken : certificates) {
        final X509CertificateHolder x509CertificateHolder = DSSUtils.getX509CertificateHolder(certificateToken);
        newCertificateStore.add(x509CertificateHolder);
    }/*ww w .j a  v  a 2s. com*/

    certificatesStore = new CollectionStore(newCertificateStore);

    final Collection<X509CRLHolder> newCrlsStore = new HashSet<X509CRLHolder>(crlsStore.getMatches(null));
    final DefaultAdvancedSignature.RevocationDataForInclusion revocationDataForInclusion = cadesSignature
            .getRevocationDataForInclusion(validationContext);
    for (final CRLToken crlToken : revocationDataForInclusion.crlTokens) {
        final X509CRLHolder x509CRLHolder = crlToken.getX509CrlHolder();
        newCrlsStore.add(x509CRLHolder);
    }
    crlsStore = new CollectionStore(newCrlsStore);

    final Collection<ASN1Primitive> newOtherRevocationInfoFormatStore = new HashSet<ASN1Primitive>(
            otherRevocationInfoFormatStoreBasic.getMatches(null));
    for (final OCSPToken ocspToken : revocationDataForInclusion.ocspTokens) {
        final BasicOCSPResp basicOCSPResp = ocspToken.getBasicOCSPResp();
        newOtherRevocationInfoFormatStore.add(DSSASN1Utils.toASN1Primitive(DSSUtils.getEncoded(basicOCSPResp)));
    }
    otherRevocationInfoFormatStoreBasic = new CollectionStore(newOtherRevocationInfoFormatStore);

    final CMSSignedDataBuilder cmsSignedDataBuilder = new CMSSignedDataBuilder(certificateVerifier);
    cmsSignedData = cmsSignedDataBuilder.regenerateCMSSignedData(cmsSignedData, parameters, certificatesStore,
            attributeCertificatesStore, crlsStore, otherRevocationInfoFormatStoreBasic,
            otherRevocationInfoFormatStoreOcsp);
    return cmsSignedData;
}

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

License:Open Source License

@Override
protected CMSSignedData postExtendCMSSignedData(CMSSignedData cmsSignedData,
        SignerInformation signerInformation, CAdESSignatureParameters parameters) {
    CAdESSignature cadesSignature = new CAdESSignature(cmsSignedData, signerInformation);
    cadesSignature.setDetachedContents(parameters.getDetachedContent());
    final ValidationContext validationContext = cadesSignature
            .getSignatureValidationContext(certificateVerifier);

    Store<X509CertificateHolder> certificatesStore = cmsSignedData.getCertificates();
    final Set<CertificateToken> certificates = cadesSignature.getCertificatesForInclusion(validationContext);
    final Collection<X509CertificateHolder> newCertificateStore = new HashSet<X509CertificateHolder>(
            certificatesStore.getMatches(null));
    for (final CertificateToken certificateToken : certificates) {
        final X509CertificateHolder x509CertificateHolder = DSSASN1Utils
                .getX509CertificateHolder(certificateToken);
        newCertificateStore.add(x509CertificateHolder);
    }/*from  w w w . j  ava2s. co m*/
    certificatesStore = new CollectionStore<X509CertificateHolder>(newCertificateStore);

    Store<X509CRLHolder> crlsStore = cmsSignedData.getCRLs();
    final Collection<X509CRLHolder> newCrlsStore = new HashSet<X509CRLHolder>(crlsStore.getMatches(null));
    final DefaultAdvancedSignature.RevocationDataForInclusion revocationDataForInclusion = cadesSignature
            .getRevocationDataForInclusion(validationContext);
    for (final CRLToken crlToken : revocationDataForInclusion.crlTokens) {
        final X509CRLHolder x509CRLHolder = getX509CrlHolder(crlToken);
        newCrlsStore.add(x509CRLHolder);
    }
    crlsStore = new CollectionStore<X509CRLHolder>(newCrlsStore);

    Store otherRevocationInfoFormatStoreBasic = cmsSignedData
            .getOtherRevocationInfo(OCSPObjectIdentifiers.id_pkix_ocsp_basic);
    final Collection<ASN1Primitive> newOtherRevocationInfoFormatStore = new HashSet<ASN1Primitive>(
            otherRevocationInfoFormatStoreBasic.getMatches(null));
    for (final OCSPToken ocspToken : revocationDataForInclusion.ocspTokens) {
        final BasicOCSPResp basicOCSPResp = ocspToken.getBasicOCSPResp();
        newOtherRevocationInfoFormatStore
                .add(DSSASN1Utils.toASN1Primitive(DSSASN1Utils.getEncoded(basicOCSPResp)));
    }
    otherRevocationInfoFormatStoreBasic = new CollectionStore(newOtherRevocationInfoFormatStore);

    Store attributeCertificatesStore = cmsSignedData.getAttributeCertificates();
    Store otherRevocationInfoFormatStoreOcsp = cmsSignedData
            .getOtherRevocationInfo(CMSObjectIdentifiers.id_ri_ocsp_response);

    final CMSSignedDataBuilder cmsSignedDataBuilder = new CMSSignedDataBuilder(certificateVerifier);
    cmsSignedData = cmsSignedDataBuilder.regenerateCMSSignedData(cmsSignedData, parameters, certificatesStore,
            attributeCertificatesStore, crlsStore, otherRevocationInfoFormatStoreBasic,
            otherRevocationInfoFormatStoreOcsp);
    return cmsSignedData;
}

From source file:net.jsign.timestamp.Timestamper.java

License:Apache License

protected CMSSignedData modifySignedData(CMSSignedData sigData, AttributeTable unsignedAttributes,
        Collection<X509CertificateHolder> extraCertificates) throws IOException, CMSException {
    SignerInformation signerInformation = sigData.getSignerInfos().getSigners().iterator().next();
    signerInformation = SignerInformation.replaceUnsignedAttributes(signerInformation, unsignedAttributes);

    Collection<X509CertificateHolder> certificates = new ArrayList<X509CertificateHolder>();
    certificates.addAll(sigData.getCertificates().getMatches(null));
    if (extraCertificates != null) {
        certificates.addAll(extraCertificates);
    }/*from ww  w. ja  va2s  .c om*/
    Store<X509CertificateHolder> certificateStore = new CollectionStore<X509CertificateHolder>(certificates);

    AuthenticodeSignedDataGenerator generator = new AuthenticodeSignedDataGenerator();
    generator.addCertificates(certificateStore);
    generator.addSigners(new SignerInformationStore(signerInformation));

    ASN1ObjectIdentifier contentType = new ASN1ObjectIdentifier(sigData.getSignedContentTypeOID());
    ASN1Encodable content = ASN1Sequence.getInstance(sigData.getSignedContent().getContent());

    return generator.generate(contentType, content);
}

From source file:org.cesecore.certificates.ca.X509CA.java

License:Open Source License

@Override
public byte[] createPKCS7(CryptoToken cryptoToken, Certificate cert, boolean includeChain)
        throws SignRequestSignatureException {
    // First verify that we signed this certificate
    try {//from   w w w  . j  a  va2s .  co  m
        if (cert != null) {
            final PublicKey verifyKey;
            final X509Certificate cacert = (X509Certificate) getCACertificate();
            if (cacert != null) {
                verifyKey = cacert.getPublicKey();
            } else {

                verifyKey = cryptoToken
                        .getPublicKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));

            }
            cert.verify(verifyKey);
        }
    } catch (CryptoTokenOfflineException e) {
        throw new SignRequestSignatureException("The cryptotoken was not available, could not create a PKCS7",
                e);
    } catch (InvalidKeyException e) {
        throw new SignRequestSignatureException("The specified certificate contains the wrong public key.", e);
    } catch (CertificateException e) {
        throw new SignRequestSignatureException("An encoding error was encountered.", e);
    } catch (NoSuchAlgorithmException e) {
        throw new SignRequestSignatureException(
                "The certificate provided was signed with an invalid algorithm.", e);
    } catch (NoSuchProviderException e) {
        throw new SignRequestSignatureException(
                "The crypto provider was not found for verification of the certificate.", e);
    } catch (SignatureException e) {
        throw new SignRequestSignatureException("Cannot verify certificate in createPKCS7(), did I sign this?",
                e);
    }

    Collection<Certificate> chain = getCertificateChain();
    ArrayList<X509CertificateHolder> certList = new ArrayList<X509CertificateHolder>();
    try {
        if (cert != null) {
            certList.add(new JcaX509CertificateHolder((X509Certificate) cert));
        }
        if (includeChain) {
            for (Certificate certificate : chain) {
                certList.add(new JcaX509CertificateHolder((X509Certificate) certificate));
            }
        }
    } catch (CertificateEncodingException e) {
        throw new SignRequestSignatureException("Could not encode certificate", e);
    }
    try {
        CMSTypedData msg = new CMSProcessableByteArray("EJBCA".getBytes());
        CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
        final PrivateKey privateKey = cryptoToken
                .getPrivateKey(getCAToken().getAliasFromPurpose(CATokenConstants.CAKEYPURPOSE_CERTSIGN));
        if (privateKey == null) {
            String msg1 = "createPKCS7: Private key does not exist!";
            log.debug(msg1);
            throw new SignRequestSignatureException(msg1);
        }
        String signatureAlgorithmName = AlgorithmTools
                .getAlgorithmNameFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privateKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(cryptoToken.getSignProviderName()).build(privateKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            gen.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) getCACertificate()));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        gen.addCertificates(new CollectionStore(certList));
        CMSSignedData s = null;
        CAToken catoken = getCAToken();
        if (catoken != null && !(cryptoToken instanceof NullCryptoToken)) {
            log.debug("createPKCS7: Provider=" + cryptoToken.getSignProviderName() + " using algorithm "
                    + privateKey.getAlgorithm());
            s = gen.generate(msg, true);
        } else {
            String msg1 = "CA Token does not exist!";
            log.debug(msg);
            throw new SignRequestSignatureException(msg1);
        }
        return s.getEncoded();
    } catch (CryptoTokenOfflineException e) {
        throw new RuntimeException(e);
    } catch (Exception e) {
        //FIXME: This right here is just nasty
        throw new RuntimeException(e);
    }
}

From source file:org.ejbca.core.model.ca.caadmin.extendedcaservices.CmsCAService.java

License:Open Source License

@Override
public ExtendedCAServiceResponse extendedService(final CryptoToken cryptoToken,
        final ExtendedCAServiceRequest request) throws ExtendedCAServiceRequestException,
        IllegalExtendedCAServiceRequestException, ExtendedCAServiceNotActiveException {
    if (log.isTraceEnabled()) {
        log.trace(">extendedService");
    }//  w w w . j  a v  a 2s .  c om
    if (!(request instanceof CmsCAServiceRequest)) {
        throw new IllegalExtendedCAServiceRequestException();
    }
    if (getStatus() != ExtendedCAServiceInfo.STATUS_ACTIVE) {
        final String msg = intres.getLocalizedMessage("caservice.notactive", "CMS");
        log.error(msg);
        throw new ExtendedCAServiceNotActiveException(msg);
    }
    ExtendedCAServiceResponse returnval = null;
    final X509Certificate signerCert = (X509Certificate) certificatechain.get(0);
    final CmsCAServiceRequest serviceReq = (CmsCAServiceRequest) request;
    // Create the signed data
    final CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();
    try {
        byte[] resp = serviceReq.getDoc();
        // Add our signer info and sign the message
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_SIGN) != 0) {
            final List<X509Certificate> x509CertChain = new ArrayList<X509Certificate>();
            for (Certificate certificate : certificatechain) {
                x509CertChain.add((X509Certificate) certificate);
            }
            gen1.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(x509CertChain)));
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            ASN1ObjectIdentifier oid = AlgorithmTools
                    .getSignAlgOidFromDigestAndKey(CMSSignedGenerator.DIGEST_SHA1, privKey.getAlgorithm());
            String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromOID(oid);
            JcaContentSignerBuilder signerBuilder = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            ContentSigner contentSigner = signerBuilder.build(privKey);
            gen1.addSignerInfoGenerator(builder.build(contentSigner, signerCert));
            final CMSTypedData msg = new CMSProcessableByteArray(resp);
            final CMSSignedData s = gen1.generate(msg, true);
            resp = s.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_ENCRYPT) != 0) {
            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(getCMSCertificate())
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                    PKCSObjectIdentifiers.des_EDE3_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
            CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(resp),
                    jceCMSContentEncryptorBuilder.build());
            resp = ed.getEncoded();
        }
        if ((serviceReq.getMode() & CmsCAServiceRequest.MODE_DECRYPT) != 0) {
            final CMSEnvelopedData ed = new CMSEnvelopedData(resp);
            final RecipientInformationStore recipients = ed.getRecipientInfos();
            final X500Name issuer = X500Name
                    .getInstance(getCMSCertificate().getIssuerX500Principal().getEncoded());
            final KeyTransRecipientId id = new KeyTransRecipientId(issuer,
                    getCMSCertificate().getSerialNumber());
            final RecipientInformation recipient = recipients.get(id);
            if (recipient != null) {
                JceKeyTransEnvelopedRecipient rec = new JceKeyTransEnvelopedRecipient(this.privKey);
                // Provider for decrypting the symmetric key 
                rec.setContentProvider(BouncyCastleProvider.PROVIDER_NAME);
                rec.setProvider(cryptoToken.getSignProviderName());
                // We can use a different provider for decrypting the content, for example of we used a PKCS#11 provider above we could use the BC provider below
                resp = recipient.getContent(rec);
            }
        }
        returnval = new CmsCAServiceResponse(resp);
    } catch (CMSException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (IOException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (OperatorCreationException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    } catch (CertificateEncodingException e) {
        log.error("Error in CmsCAService", e);
        throw new ExtendedCAServiceRequestException(e);
    }
    if (log.isTraceEnabled()) {
        log.trace("<extendedService");
    }
    return returnval;
}

From source file:org.ejbca.core.protocol.scep.ScepResponseMessage.java

License:Open Source License

@Override
public boolean create() throws CertificateEncodingException, CRLException {
    boolean ret = false;
    try {//from w w  w  .j  a va 2 s.  c  o  m
        if (status.equals(ResponseStatus.SUCCESS)) {
            log.debug("Creating a STATUS_OK message.");
        } else {
            if (status.equals(ResponseStatus.FAILURE)) {
                log.debug("Creating a STATUS_FAILED message (or returning false).");
                if (failInfo.equals(FailInfo.WRONG_AUTHORITY)) {
                    return false;
                }
                if (failInfo.equals(FailInfo.INCORRECT_DATA)) {
                    return false;
                }
            } else {
                log.debug("Creating a STATUS_PENDING message.");
            }
        }

        CMSTypedData msg;
        // Create encrypted response if this is success and NOT a CRL response message
        if (status.equals(ResponseStatus.SUCCESS)) {

            CMSEnvelopedDataGenerator edGen = new CMSEnvelopedDataGenerator();
            // Add the issued certificate to the signed portion of the CMS (as signer, degenerate case)
            List<X509Certificate> certList = new ArrayList<X509Certificate>();
            if (cert != null) {
                log.debug("Adding certificates to response message");
                certList.add((X509Certificate) cert);
                // Add the CA cert, it's optional but Cisco VPN client complains if it isn't there
                if (includeCACert) {
                    if (caCert != null) {
                        // If we have an explicit CAcertificate
                        log.debug("Including explicitly set CA certificate in SCEP response.");
                        certList.add((X509Certificate) caCert);
                    } else {
                        // If we don't have an explicit caCert, we think that the signCert is the CA cert
                        // If we have an explicit caCert, the signCert is probably the RA certificate, and we don't include that one
                        log.debug("Including message signer certificate in SCEP response.");
                        certList.add((X509Certificate) signCertChain.iterator().next());
                    }
                }
            }
            // Create the signed CMS message to be contained inside the envelope
            // this message does not contain any message, and no signerInfo
            CMSSignedDataGenerator gen = new CMSSignedDataGenerator();
            gen.addCertificates(new CollectionStore(CertTools.convertToX509CertificateHolder(certList)));
            if (crl != null) {
                gen.addCRL(new JcaX509CRLHolder((X509CRL) crl));
            }

            CMSSignedData s = gen.generate(new CMSAbsentContent(), false);

            // Envelope the CMS message
            if (recipientKeyInfo != null) {
                try {
                    X509Certificate rec = (X509Certificate) CertTools.getCertfromByteArray(recipientKeyInfo);
                    log.debug("Added recipient information - issuer: '" + CertTools.getIssuerDN(rec)
                            + "', serno: '" + CertTools.getSerialNumberAsString(rec));
                    edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator(rec)
                            .setProvider(BouncyCastleProvider.PROVIDER_NAME));
                } catch (CertificateParsingException e) {
                    throw new IllegalArgumentException("Can not decode recipients self signed certificate!", e);
                }
            } else {
                edGen.addRecipientInfoGenerator(new JceKeyTransRecipientInfoGenerator((X509Certificate) cert)
                        .setProvider(BouncyCastleProvider.PROVIDER_NAME));
            }
            try {
                JceCMSContentEncryptorBuilder jceCMSContentEncryptorBuilder = new JceCMSContentEncryptorBuilder(
                        SMIMECapability.dES_CBC).setProvider(BouncyCastleProvider.PROVIDER_NAME);
                CMSEnvelopedData ed = edGen.generate(new CMSProcessableByteArray(s.getEncoded()),
                        jceCMSContentEncryptorBuilder.build());
                if (log.isDebugEnabled()) {
                    log.debug("Enveloped data is " + ed.getEncoded().length + " bytes long");
                }
                msg = new CMSProcessableByteArray(ed.getEncoded());
            } catch (IOException e) {
                throw new IllegalStateException("Unexpected IOException caught", e);
            }
        } else {
            // Create an empty message here
            //msg = new CMSProcessableByteArray("PrimeKey".getBytes());
            msg = new CMSProcessableByteArray(new byte[0]);
        }

        // Create the outermost signed data
        CMSSignedDataGenerator gen1 = new CMSSignedDataGenerator();

        // add authenticated attributes...status, transactionId, sender- and recipientNonce and more...
        Hashtable<ASN1ObjectIdentifier, Attribute> attributes = new Hashtable<ASN1ObjectIdentifier, Attribute>();
        ASN1ObjectIdentifier oid;
        Attribute attr;
        DERSet value;

        // Message type (certrep)
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_messageType);
        value = new DERSet(new DERPrintableString("3"));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        // TransactionId
        if (transactionId != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_transId);
            log.debug("Added transactionId: " + transactionId);
            value = new DERSet(new DERPrintableString(transactionId));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // status
        oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_pkiStatus);
        value = new DERSet(new DERPrintableString(status.getStringValue()));
        attr = new Attribute(oid, value);
        attributes.put(attr.getAttrType(), attr);

        if (status.equals(ResponseStatus.FAILURE)) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_failInfo);
            log.debug("Added failInfo: " + failInfo.getValue());
            value = new DERSet(new DERPrintableString(failInfo.getValue()));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // senderNonce
        if (senderNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_senderNonce);
            log.debug("Added senderNonce: " + senderNonce);
            value = new DERSet(new DEROctetString(Base64.decode(senderNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // recipientNonce
        if (recipientNonce != null) {
            oid = new ASN1ObjectIdentifier(ScepRequestMessage.id_recipientNonce);
            log.debug("Added recipientNonce: " + recipientNonce);
            value = new DERSet(new DEROctetString(Base64.decode(recipientNonce.getBytes())));
            attr = new Attribute(oid, value);
            attributes.put(attr.getAttrType(), attr);
        }

        // Add our signer info and sign the message
        Certificate cacert = signCertChain.iterator().next();
        log.debug("Signing SCEP message with cert: " + CertTools.getSubjectDN(cacert));
        String signatureAlgorithmName = AlgorithmTools.getAlgorithmNameFromDigestAndKey(digestAlg,
                signKey.getAlgorithm());
        try {
            ContentSigner contentSigner = new JcaContentSignerBuilder(signatureAlgorithmName)
                    .setProvider(provider).build(signKey);
            JcaDigestCalculatorProviderBuilder calculatorProviderBuilder = new JcaDigestCalculatorProviderBuilder()
                    .setProvider(BouncyCastleProvider.PROVIDER_NAME);
            JcaSignerInfoGeneratorBuilder builder = new JcaSignerInfoGeneratorBuilder(
                    calculatorProviderBuilder.build());
            builder.setSignedAttributeGenerator(
                    new DefaultSignedAttributeTableGenerator(new AttributeTable(attributes)));
            gen1.addSignerInfoGenerator(builder.build(contentSigner, (X509Certificate) cacert));
        } catch (OperatorCreationException e) {
            throw new IllegalStateException("BouncyCastle failed in creating signature provider.", e);
        }
        // The un-encoded response message itself
        final CMSSignedData signedData = gen1.generate(msg, true);
        try {
            responseMessage = signedData.getEncoded();
        } catch (IOException e) {
            throw new IllegalStateException("Unexpected IOException caught.", e);
        }
        if (responseMessage != null) {
            ret = true;
        }
    } catch (CMSException e) {
        log.error("Error creating CMS message: ", e);
    }

    return ret;
}

From source file:org.xipki.pki.scep.client.Client.java

License:Open Source License

public void refresh() throws ScepClientException {
    // getCACaps// w ww  .ja  v  a  2s  .  c o  m
    ScepHttpResponse getCaCapsResp = httpSend(Operation.GetCACaps);
    this.caCaps = CaCaps.getInstance(new String(getCaCapsResp.getContentBytes()));

    // getCACert
    ScepHttpResponse getCaCertResp = httpSend(Operation.GetCACert);
    this.authorityCertStore = retrieveCaCertStore(getCaCertResp, caCertValidator);

    X509CertificateHolder certHolder;
    try {
        certHolder = new X509CertificateHolder(this.authorityCertStore.getSignatureCert().getEncoded());
    } catch (CertificateEncodingException ex) {
        throw new ScepClientException(ex);
    } catch (IOException ex) {
        throw new ScepClientException(ex);
    }
    this.responseSignerCerts = new CollectionStore<X509CertificateHolder>(Arrays.asList(certHolder));
}

From source file:org.xwiki.crypto.pkix.internal.BcX509CertificateChainBuilderTest.java

License:Open Source License

@Test
public void testValidV3CertificatePath() throws Exception {
    Collection<X509CertificateHolder> certs = new ArrayList<X509CertificateHolder>();
    certs.add(BcUtils.getX509CertificateHolder(v3CaCert));
    certs.add(BcUtils.getX509CertificateHolder(v3InterCaCert));

    CollectionStore store = new CollectionStore(certs);
    CertificateProvider provider = mocker.getInstance(CertificateProvider.class, "BCStoreX509");
    ((BcStoreX509CertificateProvider) provider).setStore(store);

    Collection<CertifiedPublicKey> chain = builder.build(v3Cert, provider);

    assertThat(chain, contains(v3CaCert, v3InterCaCert, v3Cert));
}

From source file:org.xwiki.crypto.pkix.internal.BcX509CertificateChainBuilderTest.java

License:Open Source License

@Test
public void testIncompleteV3CertificatePath() throws Exception {
    Collection<X509CertificateHolder> certs = new ArrayList<X509CertificateHolder>();
    certs.add(BcUtils.getX509CertificateHolder(v3InterCaCert));

    CollectionStore store = new CollectionStore(certs);
    CertificateProvider provider = mocker.getInstance(CertificateProvider.class, "BCStoreX509");
    ((BcStoreX509CertificateProvider) provider).setStore(store);

    Collection<CertifiedPublicKey> chain = builder.build(v3Cert, provider);

    assertThat(chain, contains(v3InterCaCert, v3Cert));
}

From source file:org.xwiki.crypto.pkix.internal.BcX509CertificateChainBuilderTest.java

License:Open Source License

@Test
public void testBrokenV3CertificatePath() throws Exception {
    Collection<X509CertificateHolder> certs = new ArrayList<X509CertificateHolder>();
    certs.add(BcUtils.getX509CertificateHolder(v3CaCert));

    CollectionStore store = new CollectionStore(certs);
    CertificateProvider provider = mocker.getInstance(CertificateProvider.class, "BCStoreX509");
    ((BcStoreX509CertificateProvider) provider).setStore(store);

    Collection<CertifiedPublicKey> chain = builder.build(v3Cert, provider);

    assertThat(chain, contains(v3Cert));
}