Example usage for org.bouncycastle.x509 X509V2CRLGenerator setSignatureAlgorithm

List of usage examples for org.bouncycastle.x509 X509V2CRLGenerator setSignatureAlgorithm

Introduction

In this page you can find the example usage for org.bouncycastle.x509 X509V2CRLGenerator setSignatureAlgorithm.

Prototype

public void setSignatureAlgorithm(String signatureAlgorithm) 

Source Link

Document

Set the signature algorithm.

Usage

From source file:chapter7.X509CRLExample.java

/**
 *
 * @param caCert//www .ja  v  a  2s . c o  m
 * @param caKey
 * @param revokedSerialNumber
 * @return
 * @throws java.lang.Exception
 */
public static X509CRL createCRL(final X509Certificate caCert, final PrivateKey caKey,
        final BigInteger revokedSerialNumber) throws Exception {
    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();

    crlGen.setIssuerDN(caCert.getSubjectX500Principal());

    crlGen.setThisUpdate(now);
    crlGen.setNextUpdate(new Date(now.getTime() + 100000));
    crlGen.setSignatureAlgorithm(CryptoDefs.Algorithm.SHA256withRSAEncryption.getName());

    crlGen.addCRLEntry(revokedSerialNumber, now, CRLReason.PRIVILEGE_WITHDRAWN.ordinal());

    crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    return crlGen.generateX509CRL(caKey, CryptoDefs.Provider.BC.getName());
}

From source file:cybervillains.ca.Generator.java

License:Open Source License

public static void main(String[] args) {
    File newCertsDir = new File(NEW_CERTS_DIR_NAME);
    newCertsDir.mkdirs();// w ww.j  ava2  s. c o  m

    // Create a new, blank KeyStore Manager
    KeyStoreManager mgr = new KeyStoreManager(newCertsDir, "blank_crl.pem");

    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();
    X509Certificate caCrlCert = null;
    try {
        caCrlCert = mgr.getSigningCert();
        PrivateKey caCrlPrivateKey = mgr.getSigningPrivateKey();

        crlGen.setIssuerDN(mgr.getSigningCert().getSubjectX500Principal());
        crlGen.setThisUpdate(now);
        crlGen.setNextUpdate(mgr.getSigningCert().getNotAfter());
        crlGen.setSignatureAlgorithm(mgr.getSigningCert().getSigAlgName());

        crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCrlCert));
        crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.ONE));

        X509CRL crl = crlGen.generate(caCrlPrivateKey);

        // You have to manually convert this file to it's PEM equivalent using OpenSSL:
        // > openssl crl -inform der -in blank_crl.dec -out blank_crl.pem

        // Save the Certificate in Binary (DEC) format
        File certRevoc = new File(newCertsDir, "blank_crl.dec");
        FileOutputStream cerOut = new FileOutputStream(certRevoc);
        byte[] buf = crl.getEncoded();
        cerOut.write(buf);
        cerOut.flush();
        cerOut.close();

        // Convert the generated DEC to PEM using OpenSSL
        Process p = Runtime.getRuntime().exec(OPENSSL_CMD_DEC_TO_PEM);
        p.waitFor();
    } catch (KeyStoreException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    } catch (CertificateParsingException e) {
        e.printStackTrace();
    } catch (NoSuchAlgorithmException e) {
        e.printStackTrace();
    } catch (UnrecoverableKeyException e) {
        e.printStackTrace();
    } catch (InvalidKeyException e) {
        e.printStackTrace();
    } catch (SignatureException e) {
        e.printStackTrace();
    } catch (CRLException e) {
        e.printStackTrace();
    } catch (InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:io.aos.crypto.spl07.X509CRLExample.java

License:Apache License

public static X509CRL createCRL(X509Certificate caCert, PrivateKey caKey, BigInteger revokedSerialNumber)
        throws Exception {
    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();

    crlGen.setIssuerDN(caCert.getSubjectX500Principal());

    crlGen.setThisUpdate(now);//from ww  w .j  av  a 2s.co m
    crlGen.setNextUpdate(new Date(now.getTime() + 100000));
    crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");

    crlGen.addCRLEntry(revokedSerialNumber, now, CRLReason.privilegeWithdrawn);

    crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    return crlGen.generateX509CRL(caKey, "BC");
}

From source file:org.apache.synapse.transport.certificatevalidation.CRLVerifierTest.java

License:Apache License

/**
 * Creates a fake CRL for the fake CA. The fake certificate with the given revokedSerialNumber will be marked
 * as Revoked in the returned CRL./*from  w  w w.j  a v  a2s .c  o m*/
 * @param caCert the fake CA certificate.
 * @param caPrivateKey private key of the fake CA.
 * @param revokedSerialNumber the serial number of the fake peer certificate made to be marked as revoked.
 * @return the created fake CRL
 * @throws Exception
 */
public static X509CRL createCRL(X509Certificate caCert, PrivateKey caPrivateKey, BigInteger revokedSerialNumber)
        throws Exception {

    X509V2CRLGenerator crlGen = new X509V2CRLGenerator();
    Date now = new Date();
    crlGen.setIssuerDN(caCert.getSubjectX500Principal());
    crlGen.setThisUpdate(now);
    crlGen.setNextUpdate(new Date(now.getTime() + TestConstants.NEXT_UPDATE_PERIOD));
    crlGen.setSignatureAlgorithm("SHA256WithRSAEncryption");
    crlGen.addCRLEntry(revokedSerialNumber, now, CRLReason.privilegeWithdrawn);
    crlGen.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
            new AuthorityKeyIdentifierStructure(caCert));
    crlGen.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    return crlGen.generateX509CRL(caPrivateKey, "BC");
}

From source file:org.candlepin.controller.CrlGeneratorTest.java

License:Open Source License

@Test
public void crlNumberWithCert() throws Exception {
    X509V2CRLGenerator g = new X509V2CRLGenerator();
    g.setIssuerDN(new X500Principal("CN=test, UID=" + UUID.randomUUID()));
    g.setThisUpdate(new Date());
    g.setNextUpdate(Util.tomorrow());
    g.setSignatureAlgorithm("SHA1withRSA");
    g.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.TEN));

    X509CRL x509crl = g.generate(KP.getPrivate());
    assertEquals(BigInteger.TEN, this.generator.getCRLNumber(x509crl));
}

From source file:org.candlepin.controller.CrlGeneratorTest.java

License:Open Source License

@Test
public void emptyRevocationsReturnsUntouched() throws Exception {
    // there's gotta be a way to reduce to a set of mocks

    KeyPair kp = CrlGeneratorTest.generateKP();
    X509V2CRLGenerator g = new X509V2CRLGenerator();
    g.setIssuerDN(new X500Principal("CN=test, UID=" + UUID.randomUUID()));
    g.setThisUpdate(new Date());
    g.setNextUpdate(Util.tomorrow());
    g.setSignatureAlgorithm("SHA1withRSA");
    g.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.TEN));
    X509CRL x509crl = g.generate(kp.getPrivate());

    // now we need to remove one of those serials
    List<CertificateSerial> toremove = new ArrayList<CertificateSerial>() {
        {//  w w  w  .j a  v a2s  . c  o m
            add(stubCS(100L, new Date()));
        }
    };

    X509CRL untouchedcrl = generator.removeEntries(x509crl, toremove);
    assertEquals(x509crl, untouchedcrl);
}

From source file:org.candlepin.controller.CrlGeneratorTest.java

License:Open Source License

@Test
@SuppressWarnings("serial")
public void removeEntries() throws Exception {
    // there's gotta be a way to reduce to a set of mocks

    KeyPair kp = CrlGeneratorTest.generateKP();
    X509V2CRLGenerator g = new X509V2CRLGenerator();
    g.setIssuerDN(new X500Principal("CN=test, UID=" + UUID.randomUUID()));
    g.setThisUpdate(new Date());
    g.setNextUpdate(Util.tomorrow());
    g.setSignatureAlgorithm("SHA1withRSA");
    g.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.TEN));
    X509CRL x509crl = g.generate(kp.getPrivate());

    List<CertificateSerial> serials = getStubCSList();
    List<X509CRLEntryWrapper> entries = Util.newList();
    for (CertificateSerial serial : serials) {
        entries.add(new X509CRLEntryWrapper(serial.getSerial(), new Date()));
        serial.setCollected(true);/*from w w  w  .j av  a  2 s . c o m*/
    }

    x509crl = pkiUtility.createX509CRL(entries, BigInteger.TEN);
    assertEquals(3, x509crl.getRevokedCertificates().size());

    // now we need to remove one of those serials
    List<CertificateSerial> toremove = new ArrayList<CertificateSerial>() {
        {
            add(stubCS(100L, new Date()));
        }
    };

    X509CRL updatedcrl = generator.removeEntries(x509crl, toremove);
    Set<? extends X509CRLEntry> revoked = updatedcrl.getRevokedCertificates();
    assertEquals(2, revoked.size());
}

From source file:org.candlepin.controller.CrlGeneratorTest.java

License:Open Source License

@Test
public void decodeValue() throws Exception {
    // there's gotta be a way to reduce to a set of mocks
    KeyPair kp = CrlGeneratorTest.generateKP();
    X509V2CRLGenerator g = new X509V2CRLGenerator();
    g.setIssuerDN(new X500Principal("CN=test, UID=" + UUID.randomUUID()));
    g.setThisUpdate(new Date());
    g.setNextUpdate(Util.tomorrow());
    g.setSignatureAlgorithm("SHA1withRSA");
    g.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.TEN));

    X509CRL x509crl = g.generate(kp.getPrivate());

    assertEquals("10", pkiUtility.decodeDERValue(x509crl.getExtensionValue(X509Extensions.CRLNumber.getId())));
}

From source file:org.candlepin.pki.impl.BouncyCastlePKIUtility.java

License:Open Source License

@Override
public X509CRL createX509CRL(List<X509CRLEntryWrapper> entries, BigInteger crlNumber) {

    try {//from   w w w .  ja  v a  2  s .c o  m
        X509Certificate caCert = reader.getCACert();
        X509V2CRLGenerator generator = new X509V2CRLGenerator();
        generator.setIssuerDN(caCert.getIssuerX500Principal());
        generator.setThisUpdate(new Date());
        generator.setNextUpdate(Util.tomorrow());
        generator.setSignatureAlgorithm(SIGNATURE_ALGO);
        // add all the CRL entries.
        for (X509CRLEntryWrapper entry : entries) {
            generator.addCRLEntry(entry.getSerialNumber(), entry.getRevocationDate(),
                    CRLReason.privilegeWithdrawn);
        }
        log.info("Completed adding CRL numbers to the certificate.");
        generator.addExtension(X509Extensions.AuthorityKeyIdentifier, false,
                new AuthorityKeyIdentifierStructure(caCert));
        generator.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(crlNumber));
        return generator.generate(reader.getCaKey());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

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

License:Open Source License

/** Generate a CRL or a deltaCRL
 * /*from   w w w . ja  va 2 s. c  om*/
 * @param certs list of revoked certificates
 * @param crlnumber CRLNumber for this CRL
 * @param isDeltaCRL true if we should generate a DeltaCRL
 * @param basecrlnumber caseCRLNumber for a delta CRL, use 0 for full CRLs
 * @param certProfile certificate profile for CRL Distribution point in the CRL, or null
 * @return CRL
 * @throws CATokenOfflineException
 * @throws IllegalKeyStoreException
 * @throws IOException
 * @throws SignatureException
 * @throws NoSuchProviderException
 * @throws InvalidKeyException
 * @throws CRLException
 * @throws NoSuchAlgorithmException
 */
private CRL generateCRL(Collection<RevokedCertInfo> certs, long crlPeriod, int crlnumber, boolean isDeltaCRL,
        int basecrlnumber)
        throws CATokenOfflineException, IllegalKeyStoreException, IOException, SignatureException,
        NoSuchProviderException, InvalidKeyException, CRLException, NoSuchAlgorithmException {
    final String sigAlg = getCAInfo().getCATokenInfo().getSignatureAlgorithm();

    if (log.isDebugEnabled()) {
        log.debug("generateCRL(" + certs.size() + ", " + crlPeriod + ", " + crlnumber + ", " + isDeltaCRL + ", "
                + basecrlnumber);
    }
    Date thisUpdate = new Date();
    Date nextUpdate = new Date();

    nextUpdate.setTime(nextUpdate.getTime() + crlPeriod);
    X509V2CRLGenerator crlgen = new X509V2CRLGenerator();
    crlgen.setThisUpdate(thisUpdate);
    crlgen.setNextUpdate(nextUpdate);
    crlgen.setSignatureAlgorithm(sigAlg);
    // Make DNs
    X509Certificate cacert = (X509Certificate) getCACertificate();
    if (cacert == null) {
        // This is an initial root CA, since no CA-certificate exists
        // (I don't think we can ever get here!!!)
        X509NameEntryConverter converter = null;
        if (getUsePrintableStringSubjectDN()) {
            converter = new PrintableStringEntryConverter();
        } else {
            converter = new X509DefaultEntryConverter();
        }

        X509Name caname = CertTools.stringToBcX509Name(getSubjectDN(), converter, getUseLdapDNOrder());
        crlgen.setIssuerDN(caname);
    } else {
        crlgen.setIssuerDN(cacert.getSubjectX500Principal());
    }
    if (certs != null) {
        Iterator<RevokedCertInfo> it = certs.iterator();
        while (it.hasNext()) {
            RevokedCertInfo certinfo = (RevokedCertInfo) it.next();
            crlgen.addCRLEntry(certinfo.getUserCertificate(), certinfo.getRevocationDate(),
                    certinfo.getReason());
        }
    }

    // Authority key identifier
    if (getUseAuthorityKeyIdentifier() == true) {
        SubjectPublicKeyInfo apki = new SubjectPublicKeyInfo((ASN1Sequence) new ASN1InputStream(
                new ByteArrayInputStream(getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN).getEncoded()))
                        .readObject());
        AuthorityKeyIdentifier aki = new AuthorityKeyIdentifier(apki);
        crlgen.addExtension(X509Extensions.AuthorityKeyIdentifier.getId(), getAuthorityKeyIdentifierCritical(),
                aki);
    }
    // CRLNumber extension
    if (getUseCRLNumber() == true) {
        CRLNumber crlnum = new CRLNumber(BigInteger.valueOf(crlnumber));
        crlgen.addExtension(X509Extensions.CRLNumber.getId(), this.getCRLNumberCritical(), crlnum);
    }

    if (isDeltaCRL) {
        // DeltaCRLIndicator extension
        CRLNumber basecrlnum = new CRLNumber(BigInteger.valueOf(basecrlnumber));
        crlgen.addExtension(X509Extensions.DeltaCRLIndicator.getId(), true, basecrlnum);
    }
    // CRL Distribution point URI and Freshest CRL DP
    if (getUseCrlDistributionPointOnCrl()) {
        String crldistpoint = getDefaultCRLDistPoint();
        List<DistributionPoint> distpoints = generateDistributionPoints(crldistpoint);

        if (distpoints.size() > 0) {
            IssuingDistributionPoint idp = new IssuingDistributionPoint(
                    distpoints.get(0).getDistributionPoint(), false, false, null, false, false);

            // According to the RFC, IDP must be a critical extension.
            // Nonetheless, at the moment, Mozilla is not able to correctly
            // handle the IDP extension and discards the CRL if it is critical.
            crlgen.addExtension(X509Extensions.IssuingDistributionPoint.getId(),
                    getCrlDistributionPointOnCrlCritical(), idp);
        }

        if (!isDeltaCRL) {
            String crlFreshestDP = getCADefinedFreshestCRL();
            List<DistributionPoint> freshestDistPoints = generateDistributionPoints(crlFreshestDP);
            if (freshestDistPoints.size() > 0) {
                CRLDistPoint ext = new CRLDistPoint((DistributionPoint[]) freshestDistPoints
                        .toArray(new DistributionPoint[freshestDistPoints.size()]));

                // According to the RFC, the Freshest CRL extension on a
                // CRL must not be marked as critical. Therefore it is
                // hardcoded as not critical and is independent of
                // getCrlDistributionPointOnCrlCritical().
                crlgen.addExtension(X509Extensions.FreshestCRL.getId(), false, ext);
            }

        }
    }

    X509CRL crl;
    crl = crlgen.generate(getCAToken().getPrivateKey(SecConst.CAKEYPURPOSE_CRLSIGN),
            getCAToken().getProvider());
    // Verify using the CA certificate before returning
    // If we can not verify the issued CRL using the CA certificate we don't want to issue this CRL
    // because something is wrong...
    PublicKey verifyKey;
    if (cacert != null) {
        verifyKey = cacert.getPublicKey();
    } else {
        verifyKey = getCAToken().getPublicKey(SecConst.CAKEYPURPOSE_CRLSIGN);
    }
    crl.verify(verifyKey);

    return crl;
}