Example usage for org.bouncycastle.cert.jcajce JcaX509CRLHolder JcaX509CRLHolder

List of usage examples for org.bouncycastle.cert.jcajce JcaX509CRLHolder JcaX509CRLHolder

Introduction

In this page you can find the example usage for org.bouncycastle.cert.jcajce JcaX509CRLHolder JcaX509CRLHolder.

Prototype

public JcaX509CRLHolder(X509CRL crl) throws CRLException 

Source Link

Document

Base constructor.

Usage

From source file:net.ripe.rpki.commons.provisioning.cms.ProvisioningCmsObjectBuilderTest.java

License:BSD License

/**
 * http://tools.ietf.org/html/draft-ietf-sidr-rescerts-provisioning-09#section-3.1.1.5
 *///from   ww  w  . ja va 2 s  .co  m
@Test
public void shouldCmsObjectHaveEmbeddedCrl() throws Exception {
    @SuppressWarnings("unchecked")
    Collection<X509CRL> crls = signedDataParser.getCRLs()
            .getMatches(new BouncyCastleUtil.X509CRLHolderStoreSelector());

    assertNotNull(crls);
    assertFalse(crls.isEmpty());
    assertEquals(new JcaX509CRLHolder(CRL), crls.iterator().next());
}

From source file:org.apache.hadoop.security.ssl.KeyStoreTestUtil.java

License:Apache License

public static X509CRL generateCRL(X509Certificate caCert, PrivateKey caPrivateKey, String signAlgorith,
        X509CRL existingCRL, BigInteger serialNumberToRevoke) throws GeneralSecurityException {
    LocalDate currentTime = LocalDate.now();
    Date nowDate = Date.from(currentTime.atStartOfDay(ZoneId.systemDefault()).toInstant());
    LocalDate nextUpdate = currentTime.plus(1, ChronoUnit.WEEKS);
    Date nextUpdateDate = Date.from(nextUpdate.atStartOfDay(ZoneId.systemDefault()).toInstant());

    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(caCert.getSubjectX500Principal().getName()),
            nowDate);//from w ww  .j a  va2 s  .  c  o  m
    crlBuilder.setNextUpdate(nextUpdateDate);
    if (existingCRL != null) {
        crlBuilder.addCRL(new JcaX509CRLHolder(existingCRL));
    }
    if (serialNumberToRevoke != null) {
        crlBuilder.addCRLEntry(serialNumberToRevoke, nowDate, CRLReason.privilegeWithdrawn);
    }
    JcaX509ExtensionUtils extUtils = new JcaX509ExtensionUtils();
    try {
        crlBuilder.addExtension(Extension.authorityKeyIdentifier, false,
                extUtils.createAuthorityKeyIdentifier(caCert.getPublicKey()));
        crlBuilder.addExtension(Extension.cRLNumber, false, new CRLNumber(BigInteger.ONE));
        X509CRLHolder crlHolder = crlBuilder
                .build(new JcaContentSignerBuilder(signAlgorith).setProvider("BC").build(caPrivateKey));
        return new JcaX509CRLConverter().setProvider("BC").getCRL(crlHolder);
    } catch (CertIOException | OperatorCreationException ex) {
        throw new GeneralSecurityException(ex);
    }
}

From source file:org.cryptable.pki.communication.PKICMPMessagesTest.java

License:Open Source License

private byte[] createRevocationRespons1(byte[] senderNonce, byte[] transactionId)
        throws CRLException, CMPException, CertificateEncodingException, OperatorCreationException,
        PKICMPMessageException, IOException {

    RevRepContentBuilder revRepContentBuilder = new RevRepContentBuilder();
    revRepContentBuilder.add(new PKIStatusInfo(PKIStatus.granted),
            new CertId(new GeneralName(JcaX500NameUtil.getIssuer(pki.getRevokedCert())),
                    pki.getRevokedCert().getSerialNumber()));
    revRepContentBuilder.addCrl(new JcaX509CRLHolder(pki.getX509CRL()).toASN1Structure());

    PKIBody pkiBody = new PKIBody(PKIBody.TYPE_REVOCATION_REP, revRepContentBuilder.build());

    return createProtectedPKIMessage(senderNonce, transactionId, pkiBody);

}

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 ww  w. ja va  2s  .  c om*/
        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;
}