Example usage for org.bouncycastle.asn1.x500 X500Name X500Name

List of usage examples for org.bouncycastle.asn1.x500 X500Name X500Name

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500 X500Name X500Name.

Prototype

public X500Name(String dirName) 

Source Link

Usage

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

License:Apache License

/**
 * Creates a Certificate Revocation List (CRL) for the certificate serialnumbers given.
 *
 * @param revokedCerts  List of the serialnumbers that should be revoked.
 *//*from w  ww.j  a v  a 2  s . c o m*/
public void generateRootCACRL(String signName,
        List<net.maritimecloud.identityregistry.model.database.Certificate> revokedCerts,
        PrivateKeyEntry keyEntry, String outputCaCrlPath) {
    Date now = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(now);
    cal.add(Calendar.YEAR, 1);
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(signName), now);
    crlBuilder.setNextUpdate(cal.getTime()); // The next CRL is next year (dummy value)
    if (revokedCerts != null) {
        for (net.maritimecloud.identityregistry.model.database.Certificate cert : revokedCerts) {
            String certReason = cert.getRevokeReason().toLowerCase();
            int reason = getCRLReasonFromString(certReason);
            crlBuilder.addCRLEntry(cert.getSerialNumber(), cert.getRevokedAt(), reason);
        }
    }
    //crlBuilder.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    //crlBuilder.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    JcaContentSignerBuilder signBuilder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    signBuilder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer;
    try {
        signer = signBuilder.build(keyEntry.getPrivateKey());
    } catch (OperatorCreationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return;
    }

    X509CRLHolder cRLHolder = crlBuilder.build(signer);
    JcaX509CRLConverter converter = new JcaX509CRLConverter();
    converter.setProvider(BC_PROVIDER_NAME);
    X509CRL crl;
    try {
        crl = converter.getCRL(cRLHolder);
    } catch (CRLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String pemCrl;
    try {
        pemCrl = CertificateUtil.getPemFromEncoded("X509 CRL", crl.getEncoded());
    } catch (CRLException e) {
        log.warn("unable to generate RootCACRL", e);
        return;
    }
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputCaCrlPath));
        writer.write(pemCrl);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.maritimecloud.identityregistry.utils.CertificateUtil.java

License:Apache License

public UserDetails getUserFromCert(X509Certificate userCertificate) {
    String certDN = userCertificate.getSubjectDN().getName();
    X500Name x500name = new X500Name(certDN);
    InetOrgPerson.Essence essence = new InetOrgPerson.Essence();
    String name = getElement(x500name, BCStyle.CN);
    String uid = getElement(x500name, BCStyle.UID);
    essence.setUsername(uid);/*  www.  j  a v a  2 s .c o m*/
    essence.setUid(uid);
    essence.setDn(certDN);
    essence.setCn(new String[] { name });
    essence.setSn(name);
    essence.setO(getElement(x500name, BCStyle.O));
    essence.setOu(getElement(x500name, BCStyle.OU));
    essence.setDescription(certDN);
    // Hack alert! There is no country property in this type, so we misuse PostalAddress...
    essence.setPostalAddress(getElement(x500name, BCStyle.C));
    log.debug("Parsed certificate, name: " + name);

    // Extract info from Subject Alternative Name extension
    Collection<List<?>> san = null;
    try {
        san = userCertificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        log.warn("could not extract info from Subject Alternative Names - will be ignored.");
    }
    // Check that the certificate includes the SubjectAltName extension
    if (san != null) {
        // Use the type OtherName to search for the certified server name
        Collection<GrantedAuthority> roles = new ArrayList<>();
        for (List item : san) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                // Type OtherName found so return the associated value
                ASN1InputStream decoder = null;
                String oid = "";
                String value = "";
                try {
                    // Value is encoded using ASN.1 so decode it to get it out again
                    decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DLSequence seq = (DLSequence) decoder.readObject();
                    ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    ASN1Encodable encoded = seq.getObjectAt(1);
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    oid = asnOID.getId();
                    value = ((DERUTF8String) encoded).getString();
                } catch (UnsupportedEncodingException e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } catch (Exception e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } finally {
                    if (decoder != null) {
                        try {
                            decoder.close();
                        } catch (IOException e) {
                        }
                    }
                }
                log.debug("oid: " + oid + ", value: " + value);
                switch (oid) {
                case MC_OID_FLAGSTATE:
                case MC_OID_CALLSIGN:
                case MC_OID_IMO_NUMBER:
                case MC_OID_MMSI_NUMBER:
                case MC_OID_AIS_SHIPTYPE:
                case MC_OID_PORT_OF_REGISTER:
                    log.debug("Ship specific OIDs are ignored");
                    break;
                case MC_OID_MRN:
                    // We only support 1 mrn
                    essence.setUid(value);
                    break;
                case MC_OID_PERMISSIONS:
                    if (value != null && !value.trim().isEmpty()) {
                        SimpleGrantedAuthority role = new SimpleGrantedAuthority(value);
                        roles.add(role);
                    }
                    break;
                default:
                    log.error("Unknown OID!");
                    break;
                }
            } else {
                // Other types are not supported so ignore them
                log.warn("SubjectAltName of invalid type found: " + type);
            }
        }
        if (!roles.isEmpty()) {
            essence.setAuthorities(roles);
        }
    }
    return essence.createUserDetails();
}

From source file:net.maritimecloud.pki.CAHandler.java

License:Apache License

/**
 * Creates a sub Certificate Authority for the MC PKI. The certificate and keypair is placed in a "SubCaKeystore"
 * defined in PKIConfiguration and in the truststore, also defined in PKIConfiguration. The SubCaKeystore will be
 * created if it does not exist already, but the truststore is expected to exists already. It is also expected that
 * a RootCaKeystore is defined in PKIConfiguration and exists.
 *
 * @param subCaCertDN The DN of the new sub CA certificate.
 */// w  w w  .  ja  v  a 2s. c om
public void createSubCa(String subCaCertDN) {

    // Open the various keystores
    KeyStore rootKeystore;
    InputStream rootKeystoreIS = null;
    KeyStore subCaKeystore;
    KeyStore truststore;
    FileInputStream subCaFis = null;
    FileInputStream trustFis = null;
    try {
        // Open the root keystore
        rootKeystore = KeyStore.getInstance(KEYSTORE_TYPE);
        rootKeystoreIS = new FileInputStream(pkiConfiguration.getRootCaKeystorePath());
        rootKeystore.load(rootKeystoreIS, pkiConfiguration.getRootCaKeystorePassword().toCharArray());

        // Open or create the sub CA keystore
        subCaKeystore = KeyStore.getInstance(KEYSTORE_TYPE);
        if (new File(pkiConfiguration.getSubCaKeystorePath()).exists()) {
            subCaFis = new FileInputStream(pkiConfiguration.getSubCaKeystorePath());
            subCaKeystore.load(subCaFis, pkiConfiguration.getSubCaKeystorePassword().toCharArray());
        } else {
            subCaKeystore.load(null, pkiConfiguration.getSubCaKeystorePassword().toCharArray());
        }

        // Open the truststore
        trustFis = new FileInputStream(pkiConfiguration.getTruststorePath());
        truststore = KeyStore.getInstance(KeyStore.getDefaultType());
        truststore.load(trustFis, pkiConfiguration.getTruststorePassword().toCharArray());

    } catch (KeyStoreException | CertificateException | NoSuchAlgorithmException | IOException e) {
        throw new RuntimeException(e);
    } finally {
        safeClose(rootKeystoreIS);
        safeClose(trustFis);
        safeClose(subCaFis);
    }

    // Extract the root certificate
    KeyStore.ProtectionParameter protParam = new KeyStore.PasswordProtection(
            pkiConfiguration.getRootCaKeystorePassword().toCharArray());
    KeyStore.PrivateKeyEntry rootCertEntry;
    X500Name rootCertX500Name;
    String crlUrl;
    try {
        rootCertEntry = (KeyStore.PrivateKeyEntry) rootKeystore.getEntry(ROOT_CERT_ALIAS, protParam);
        rootCertX500Name = new JcaX509CertificateHolder((X509Certificate) rootCertEntry.getCertificate())
                .getSubject();
    } catch (NoSuchAlgorithmException | UnrecoverableEntryException | KeyStoreException
            | CertificateEncodingException e) {
        throw new RuntimeException(e);
    }
    try {
        List<String> crlPoints = CRLVerifier
                .getCrlDistributionPoints((X509Certificate) rootCertEntry.getCertificate());
        crlUrl = crlPoints.get(0);
    } catch (CertificateParsingException | IOException e) {
        throw new RuntimeException(e);
    }

    // Create the sub CA certificate
    KeyPair subCaKeyPair = CertificateBuilder.generateKeyPair();
    X509Certificate subCaCert;
    X500Name subCaCertX500Name = new X500Name(subCaCertDN);
    String alias = CertificateHandler.getElement(subCaCertX500Name, BCStyle.UID);
    if (alias == null || alias.trim().isEmpty()) {
        throw new RuntimeException("UID must be defined for sub CA! It will be used as the sub CA alias.");
    }
    try {
        subCaCert = certificateBuilder.buildAndSignCert(certificateBuilder.generateSerialNumber(),
                rootCertEntry.getPrivateKey(), rootCertEntry.getCertificate().getPublicKey(),
                subCaKeyPair.getPublic(), rootCertX500Name, subCaCertX500Name, null, "INTERMEDIATE", null,
                crlUrl);
    } catch (Exception e) {
        throw new RuntimeException("Could not create sub CA certificate!", e);
    }

    // Store the sub CA certificate in the Sub CA keystore and the MC truststore
    FileOutputStream trustFos = null;
    FileOutputStream subCaFos = null;
    try {
        Certificate[] certChain = new Certificate[2];
        certChain[0] = subCaCert;
        certChain[1] = rootCertEntry.getCertificate();
        subCaFos = new FileOutputStream(pkiConfiguration.getSubCaKeystorePath());
        subCaKeystore.setKeyEntry(alias, subCaKeyPair.getPrivate(),
                pkiConfiguration.getSubCaKeyPassword().toCharArray(), certChain);
        subCaKeystore.store(subCaFos, pkiConfiguration.getSubCaKeystorePassword().toCharArray());

        trustFos = new FileOutputStream(pkiConfiguration.getTruststorePath());
        truststore.setCertificateEntry(alias, subCaCert);
        truststore.store(trustFos, pkiConfiguration.getTruststorePassword().toCharArray());

    } catch (NoSuchAlgorithmException | KeyStoreException | CertificateException | IOException e) {
        throw new RuntimeException(e);
    } finally {
        safeClose(trustFos);
        safeClose(subCaFos);
    }

}

From source file:net.maritimecloud.pki.CAHandler.java

License:Apache License

/**
 * Generates a self-signed certificate and saves it in the keystore and truststore.
 * Should only be used to init the root CA. It is expected that info about the root keystore and the truststore
 * is available in PKIConfiguration. If they already exists they will be overwritten!
 *
 * @param rootCertX500Name The DN of the new root CA Certificate
 * @param crlUrl CRL endpoint/*from  w  w  w . j  a v  a2 s. c  o  m*/
 */
public void initRootCA(String rootCertX500Name, String crlUrl) {
    KeyPair cakp = CertificateBuilder.generateKeyPair();
    KeyStore rootks;
    KeyStore ts;
    FileOutputStream rootfos = null;
    FileOutputStream tsfos = null;
    try {
        rootks = KeyStore.getInstance(KEYSTORE_TYPE);
        rootks.load(null, pkiConfiguration.getRootCaKeystorePassword().toCharArray());
        // Store away the keystore.
        rootfos = new FileOutputStream(pkiConfiguration.getRootCaKeystorePath());
        X509Certificate cacert;
        try {
            cacert = certificateBuilder.buildAndSignCert(certificateBuilder.generateSerialNumber(),
                    cakp.getPrivate(), cakp.getPublic(), cakp.getPublic(), new X500Name(rootCertX500Name),
                    new X500Name(rootCertX500Name), null, "ROOTCA", null, crlUrl);
        } catch (Exception e) {
            throw new RuntimeException(e.getMessage(), e);
        }

        Certificate[] certChain = new Certificate[1];
        certChain[0] = cacert;
        rootks.setKeyEntry(ROOT_CERT_ALIAS, cakp.getPrivate(),
                pkiConfiguration.getRootCaKeyPassword().toCharArray(), certChain);
        rootks.store(rootfos, pkiConfiguration.getRootCaKeystorePassword().toCharArray());
        rootks = KeyStore.getInstance(KeyStore.getDefaultType());
        rootks.load(null, pkiConfiguration.getRootCaKeystorePassword().toCharArray());

        // Store away the truststore.
        ts = KeyStore.getInstance(KeyStore.getDefaultType());
        ts.load(null, pkiConfiguration.getTruststorePassword().toCharArray());
        tsfos = new FileOutputStream(pkiConfiguration.getTruststorePath());
        ts.setCertificateEntry(ROOT_CERT_ALIAS, cacert);
        ts.store(tsfos, pkiConfiguration.getTruststorePassword().toCharArray());
    } catch (KeyStoreException | NoSuchAlgorithmException | CertificateException | IOException e) {
        throw new RuntimeException(e.getMessage(), e);
    } finally {
        safeClose(rootfos);
        safeClose(tsfos);
    }
}

From source file:net.maritimecloud.pki.CertificateBuilder.java

License:Apache License

/**
 * Generates a signed certificate for an entity.
 *
 * @param country The country of org/entity
 * @param orgName The name of the organization the entity belongs to
 * @param type The type of the  entity//ww w.  j  av  a  2 s.c om
 * @param callName The name of the entity
 * @param email The email of the entity
 * @param publickey The public key of the entity
 * @param baseCrlOcspURI The base URI used for the CRL and OCSP endpoint. This will be prepended: (ocsp|crl)/urn:mrn:mcl:ca:...
 * @return Returns a signed X509Certificate
 */
public X509Certificate generateCertForEntity(BigInteger serialNumber, String country, String orgName,
        String type, String callName, String email, String uid, PublicKey publickey,
        Map<String, String> customAttr, String signingAlias, String baseCrlOcspURI) throws Exception {
    KeyStore.PrivateKeyEntry signingCertEntry = keystoreHandler.getSigningCertEntry(signingAlias);
    Certificate signingCert = signingCertEntry.getCertificate();
    X509Certificate signingX509Cert = (X509Certificate) signingCert;
    // Try to find the correct country code, else we just use the country name as code
    String orgCountryCode = country;
    String[] locales = Locale.getISOCountries();
    for (String countryCode : locales) {
        Locale loc = new Locale("", countryCode);
        if (loc.getDisplayCountry(Locale.ENGLISH).equals(orgCountryCode)) {
            orgCountryCode = loc.getCountry();
            break;
        }
    }

    HashMap<String, String> commasConverted = convertCommas(orgName, type, callName, uid);

    String orgSubjectDn = "C=" + orgCountryCode + ", " + "O=" + commasConverted.get("orgName") + ", " + "OU="
            + commasConverted.get("type") + ", " + "CN=" + commasConverted.get("callName") + ", " + "UID="
            + commasConverted.get("uid");
    if (email != null && !email.isEmpty()) {
        orgSubjectDn += ", E=" + email;
    }
    X500Name subCaCertX500Name = new X500Name(signingX509Cert.getSubjectDN().getName());
    String alias = CertificateHandler.getElement(subCaCertX500Name, BCStyle.UID);
    String ocspUrl = baseCrlOcspURI + "ocsp/" + alias;
    String crlUrl = baseCrlOcspURI + "crl/" + alias;
    return buildAndSignCert(serialNumber, signingCertEntry.getPrivateKey(), signingX509Cert.getPublicKey(),
            publickey, new JcaX509CertificateHolder(signingX509Cert).getSubject(), new X500Name(orgSubjectDn),
            customAttr, "ENTITY", ocspUrl, crlUrl);
}

From source file:net.maritimecloud.pki.CertificateHandler.java

License:Apache License

/**
 * Extracts a PKIIdentity from a certificate using the MC PKI certificate "format"
 *
 * @param userCertificate The certificate
 * @return The extracted identity/*from  w  ww .j a va 2 s.  co  m*/
 */
public static PKIIdentity getIdentityFromCert(X509Certificate userCertificate) {
    PKIIdentity identity = new PKIIdentity();
    String certDN = userCertificate.getSubjectDN().getName();
    X500Name x500name = new X500Name(certDN);
    String name = getElement(x500name, BCStyle.CN);
    String uid = getElement(x500name, BCStyle.UID);
    identity.setMrn(uid);
    identity.setDn(certDN);
    identity.setCn(name);
    identity.setSn(name);
    identity.setO(getElement(x500name, BCStyle.O));
    identity.setOu(getElement(x500name, BCStyle.OU));
    identity.setCountry(getElement(x500name, BCStyle.C));
    identity.setEmail(getElement(x500name, BCStyle.EmailAddress));
    // Extract first and last name from full name
    String lastName = "";
    String firstName = "";
    if (name.split("\\w +\\w").length > 1) {
        lastName = name.substring(name.lastIndexOf(" ") + 1);
        firstName = name.substring(0, name.lastIndexOf(' '));
    } else {
        firstName = name;
    }
    identity.setFirstName(firstName);
    identity.setLastName(lastName);
    log.debug("Parsed certificate, name: " + name);

    // Extract info from Subject Alternative Name extension
    Collection<List<?>> san = null;
    try {
        san = userCertificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        log.warn("could not extract info from Subject Alternative Names - will be ignored.");
    }
    // Check that the certificate includes the SubjectAltName extension
    if (san != null) {
        // Use the type OtherName to search for the certified server name
        StringBuilder permissions = new StringBuilder();
        for (List item : san) {
            Integer type = (Integer) item.get(0);
            if (type == 0) {
                // Type OtherName found so return the associated value
                ASN1InputStream decoder = null;
                String oid;
                String value;
                try {
                    // Value is encoded using ASN.1 so decode it to get it out again
                    decoder = new ASN1InputStream((byte[]) item.toArray()[1]);
                    DLSequence seq = (DLSequence) decoder.readObject();
                    ASN1ObjectIdentifier asnOID = (ASN1ObjectIdentifier) seq.getObjectAt(0);
                    ASN1Encodable encoded = seq.getObjectAt(1);
                    oid = asnOID.getId();
                    // For some weird reason we need to do this 2 times - otherwise we get a
                    // ClassCastException when extracting the value.
                    encoded = ((DERTaggedObject) encoded).getObject();
                    encoded = ((DERTaggedObject) encoded).getObject();
                    value = ((DERUTF8String) encoded).getString();
                } catch (UnsupportedEncodingException e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } catch (Exception e) {
                    log.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } finally {
                    if (decoder != null) {
                        try {
                            decoder.close();
                        } catch (IOException e) {
                            e.printStackTrace();
                        }
                    }
                }
                log.debug("oid: " + oid + ", value: " + value);
                switch (oid) {
                case MC_OID_FLAGSTATE:
                    identity.setFlagState(value);
                    break;
                case MC_OID_CALLSIGN:
                    identity.setCallSign(value);
                    break;
                case MC_OID_IMO_NUMBER:
                    identity.setImoNumber(value);
                    break;
                case MC_OID_MMSI_NUMBER:
                    identity.setMmsiNumber(value);
                    break;
                case MC_OID_AIS_SHIPTYPE:
                    identity.setAisShipType(value);
                    break;
                case MC_OID_PORT_OF_REGISTER:
                    identity.setPortOfRegister(value);
                    break;
                case MC_OID_MRN:
                    // We only support 1 mrn
                    identity.setMrn(value);
                    break;
                case MC_OID_SHIP_MRN:
                    identity.setShipMrn(value);
                case MC_OID_PERMISSIONS:
                    if (value != null && !value.trim().isEmpty()) {
                        if (permissions.length() == 0) {
                            permissions = new StringBuilder(value);
                        } else {
                            permissions.append(',').append(value);
                        }
                    }
                    break;
                default:
                    log.error("Unknown OID!");
                    break;
                }
            } else {
                // Other types are not supported so ignore them
                log.warn("SubjectAltName of invalid type found: " + type);
            }
        }
        if (permissions.length() > 0) {
            identity.setPermissions(permissions.toString());
        }
    }
    return identity;
}

From source file:net.maritimecloud.pki.OCSPVerifier.java

License:Apache License

/**
 * Verifies a certificate against a its issuer using OCSP. In most cases you should probably use
 * {@link CertificateHandler#verifyCertificateChain(X509Certificate, KeyStore) verifyCertificateChain}
 * instead to verify the complete chain.
 *
 * @param cert Certificate to validate//  w  ww .java  2 s .  com
 * @param trustStore Truststore containing the issuer certificate
 * @return
 * @throws IOException
 * @throws KeyStoreException
 * @throws OCSPValidationException
 */
public static RevocationInfo verifyCertificateOCSP(X509Certificate cert, KeyStore trustStore)
        throws IOException, KeyStoreException, OCSPValidationException {
    X500Name x500name = new X500Name(cert.getIssuerDN().getName());
    String issuerAlias = CertificateHandler.getElement(x500name, BCStyle.UID);
    X509Certificate issuerCert = (X509Certificate) trustStore.getCertificate(issuerAlias);
    return verifyCertificateOCSP(cert, issuerCert);
}

From source file:net.maritimecloud.pki.Revocation.java

License:Apache License

/**
 * Creates a Certificate RevocationInfo List (CRL) for the certificate serialnumbers given.
 *
 * @param revokedCerts  List of the serialnumbers that should be revoked.
 * @param keyEntry Private key to sign the CRL
 * @return a CRL//from   w w w. ja va 2 s  . co  m
 */
public static X509CRL generateCRL(List<RevocationInfo> revokedCerts, KeyStore.PrivateKeyEntry keyEntry) {
    Date now = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(now);
    cal.add(Calendar.DATE, 7);
    String signCertX500Name;
    try {
        signCertX500Name = new JcaX509CertificateHolder((X509Certificate) keyEntry.getCertificate())
                .getSubject().toString();
    } catch (CertificateEncodingException e) {
        e.printStackTrace();
        return null;
    }
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(signCertX500Name), now);
    crlBuilder.setNextUpdate(new Date(now.getTime() + 24 * 60 * 60 * 1000 * 7)); // The next CRL is next week (dummy value)
    for (RevocationInfo cert : revokedCerts) {
        crlBuilder.addCRLEntry(cert.getSerialNumber(), cert.getRevokedAt(), cert.getRevokeReason().ordinal());
    }
    //crlBuilder.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    //crlBuilder.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    JcaContentSignerBuilder signBuilder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    signBuilder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer;
    try {
        signer = signBuilder.build(keyEntry.getPrivateKey());
    } catch (OperatorCreationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return null;
    }

    X509CRLHolder cRLHolder = crlBuilder.build(signer);
    JcaX509CRLConverter converter = new JcaX509CRLConverter();
    converter.setProvider(BC_PROVIDER_NAME);
    X509CRL crl = null;
    try {
        crl = converter.getCRL(cRLHolder);
    } catch (CRLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return crl;
}

From source file:net.maritimecloud.pki.Revocation.java

License:Apache License

/**
 * Creates a Certificate RevocationInfo List (CRL) for the certificate serialnumbers given.
 *
 * @param signName DN name of the signing certificate
 * @param revokedCerts  List of the serialnumbers that should be revoked.
 * @param keyEntry Private key to sign the CRL
 * @param outputCaCrlPath Where to place the CRL
 *//*  w ww . j  a va2  s .  c  o m*/
public static void generateRootCACRL(String signName, List<RevocationInfo> revokedCerts,
        KeyStore.PrivateKeyEntry keyEntry, String outputCaCrlPath) {
    Date now = new Date();
    Calendar cal = Calendar.getInstance();
    cal.setTime(now);
    cal.add(Calendar.YEAR, 1);
    X509v2CRLBuilder crlBuilder = new X509v2CRLBuilder(new X500Name(signName), now);
    crlBuilder.setNextUpdate(cal.getTime()); // The next CRL is next year (dummy value)
    if (revokedCerts != null) {
        for (RevocationInfo cert : revokedCerts) {
            crlBuilder.addCRLEntry(cert.getSerialNumber(), cert.getRevokedAt(),
                    cert.getRevokeReason().ordinal());
        }
    }
    //crlBuilder.addExtension(X509Extensions.AuthorityKeyIdentifier, false, new AuthorityKeyIdentifierStructure(caCert));
    //crlBuilder.addExtension(X509Extensions.CRLNumber, false, new CRLNumber(BigInteger.valueOf(1)));

    JcaContentSignerBuilder signBuilder = new JcaContentSignerBuilder(SIGNER_ALGORITHM);
    signBuilder.setProvider(BC_PROVIDER_NAME);
    ContentSigner signer;
    try {
        signer = signBuilder.build(keyEntry.getPrivateKey());
    } catch (OperatorCreationException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
        return;
    }

    X509CRLHolder cRLHolder = crlBuilder.build(signer);
    JcaX509CRLConverter converter = new JcaX509CRLConverter();
    converter.setProvider(BC_PROVIDER_NAME);
    X509CRL crl;
    try {
        crl = converter.getCRL(cRLHolder);
    } catch (CRLException e) {
        throw new RuntimeException(e.getMessage(), e);
    }
    String pemCrl;
    try {
        pemCrl = getPemFromEncoded("X509 CRL", crl.getEncoded());
    } catch (CRLException e) {
        //log.warn("unable to generate RootCACRL", e);
        return;
    }
    try {
        BufferedWriter writer = new BufferedWriter(new FileWriter(outputCaCrlPath));
        writer.write(pemCrl);
        writer.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

From source file:net.markenwerk.utils.mail.smime.SmimeUtil.java

License:Open Source License

private static IssuerAndSerialNumber getIssuerAndSerialNumber(SmimeKey smimeKey) {
    X509Certificate certificate = smimeKey.getCertificate();
    BigInteger serialNumber = certificate.getSerialNumber();
    X500Name issuerName = new X500Name(certificate.getIssuerDN().getName());
    IssuerAndSerialNumber issuerAndSerialNumber = new IssuerAndSerialNumber(issuerName, serialNumber);
    return issuerAndSerialNumber;
}