Example usage for org.bouncycastle.asn1.x500.style BCStyle UID

List of usage examples for org.bouncycastle.asn1.x500.style BCStyle UID

Introduction

In this page you can find the example usage for org.bouncycastle.asn1.x500.style BCStyle UID.

Prototype

ASN1ObjectIdentifier UID

To view the source code for org.bouncycastle.asn1.x500.style BCStyle UID.

Click Source Link

Document

LDAP User id.

Usage

From source file:com.spotify.helios.client.tls.X509CertificateFactory.java

License:Apache License

private CertificateAndPrivateKey generate(final AgentProxy agentProxy, final Identity identity,
        final String username) {

    final UUID uuid = new UUID();
    final Calendar calendar = Calendar.getInstance();
    final X500Name issuerDN = new X500Name("C=US,O=Spotify,CN=helios-client");
    final X500Name subjectDN = new X500NameBuilder().addRDN(BCStyle.UID, username).build();

    calendar.add(Calendar.MILLISECOND, -validBeforeMilliseconds);
    final Date notBefore = calendar.getTime();

    calendar.add(Calendar.MILLISECOND, validBeforeMilliseconds + validAfterMilliseconds);
    final Date notAfter = calendar.getTime();

    // Reuse the UUID time as a SN
    final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();

    try {/*from   www. j  av  a2  s  .  c o  m*/
        final KeyPairGenerator keyPairGenerator = KeyPairGenerator.getInstance("RSA", "BC");
        keyPairGenerator.initialize(KEY_SIZE, new SecureRandom());

        final KeyPair keyPair = keyPairGenerator.generateKeyPair();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
                .getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));

        final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
                notAfter, subjectDN, subjectPublicKeyInfo);

        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);

        final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
        final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
        log.info("generating an X509 certificate for {} with key ID={} and identity={}", username, keyIdHex,
                identity.getComment());

        builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
        builder.addExtension(Extension.authorityKeyIdentifier, false,
                utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));

        final X509CertificateHolder holder = builder.build(new SshAgentContentSigner(agentProxy, identity));

        final X509Certificate certificate = CERTIFICATE_CONVERTER.getCertificate(holder);
        log.debug("generated certificate:\n{}", asPEMString(certificate));

        return new CertificateAndPrivateKey(certificate, keyPair.getPrivate());
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:com.spotify.sshagenttls.X509CertKeyCreator.java

License:Apache License

@Override
public CertKey createCertKey(final String username, final X500Principal x500Principal) {
    final Calendar calendar = Calendar.getInstance();
    final BigInteger serialNumber = BigInteger.valueOf(calendar.getTimeInMillis()).abs();
    final X500Name issuerDn = new X500Name(x500Principal.getName(X500Principal.RFC1779));
    final X500Name subjectDn = new X500NameBuilder().addRDN(BCStyle.UID, username).build();

    calendar.add(Calendar.MILLISECOND, -validBeforeMillis);
    final Date notBefore = calendar.getTime();

    calendar.add(Calendar.MILLISECOND, validBeforeMillis + validAfterMillis);
    final Date notAfter = calendar.getTime();

    try {//from w w w .  j  a va  2s.  c o  m
        final KeyPair keyPair = generateRandomKeyPair();
        final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
                .getInstance(ASN1Sequence.getInstance(keyPair.getPublic().getEncoded()));

        final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerDn, serialNumber, notBefore,
                notAfter, subjectDn, subjectPublicKeyInfo);

        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);

        final SubjectKeyIdentifier keyId = utils.createSubjectKeyIdentifier(subjectPublicKeyInfo);
        final String keyIdHex = KEY_ID_ENCODING.encode(keyId.getKeyIdentifier());
        LOG.info("generating an X.509 certificate for {} with key ID={}", username, keyIdHex);

        builder.addExtension(Extension.subjectKeyIdentifier, false, keyId);
        builder.addExtension(Extension.authorityKeyIdentifier, false,
                utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));

        final X509CertificateHolder holder = builder.build(contentSigner);

        final X509Certificate cert = CERT_CONVERTER.getCertificate(holder);
        LOG.debug("generated certificate:\n{}", Utils.asPemString(cert));

        return CertKey.create(cert, keyPair.getPrivate());
    } catch (Exception e) {
        throw new RuntimeException(e);
    }
}

From source file:com.spotify.sshtlsclient.X509CertificateFactory.java

License:Apache License

static Certificate get(final SshAgentContentSigner signer, final Identity identity, final String username) {
    final UUID uuid = new UUID();
    final Calendar calendar = Calendar.getInstance();
    final X500Name issuerDN = new X500Name("C=US,O=Spotify,CN=helios-client");
    final X500Name subjectDN = new X500NameBuilder().addRDN(BCStyle.UID, username).build();
    final SubjectPublicKeyInfo subjectPublicKeyInfo = SubjectPublicKeyInfo
            .getInstance(ASN1Sequence.getInstance(identity.getPublicKey().getEncoded()));

    calendar.add(Calendar.HOUR, -HOURS_BEFORE);
    final Date notBefore = calendar.getTime();

    calendar.add(Calendar.HOUR, HOURS_BEFORE + HOURS_AFTER);
    final Date notAfter = calendar.getTime();

    // Reuse the UUID time as a SN
    final BigInteger serialNumber = BigInteger.valueOf(uuid.getTime()).abs();

    final X509v3CertificateBuilder builder = new X509v3CertificateBuilder(issuerDN, serialNumber, notBefore,
            notAfter, subjectDN, subjectPublicKeyInfo);

    try {//from   ww  w  .ja va  2  s .c  o  m
        final DigestCalculator digestCalculator = new BcDigestCalculatorProvider()
                .get(new AlgorithmIdentifier(OIWObjectIdentifiers.idSHA1));
        final X509ExtensionUtils utils = new X509ExtensionUtils(digestCalculator);

        builder.addExtension(Extension.subjectKeyIdentifier, false,
                utils.createSubjectKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.authorityKeyIdentifier, false,
                utils.createAuthorityKeyIdentifier(subjectPublicKeyInfo));
        builder.addExtension(Extension.keyUsage, false,
                new KeyUsage(KeyUsage.digitalSignature | KeyUsage.keyCertSign));
        builder.addExtension(Extension.basicConstraints, true, new BasicConstraints(false));

        final X509CertificateHolder holder = builder.build(signer);

        return new Certificate(new org.bouncycastle.asn1.x509.Certificate[] { holder.toASN1Structure(), });
    } catch (Exception e) {
        throw Throwables.propagate(e);
    }
}

From source file:net.maritimecloud.identityregistry.keycloak.spi.authenticators.certificate.utils.CertificateUtil.java

License:Apache License

public Map<String, String> getUserFromCert(X509Certificate userCertificate) {
    Map<String, String> user = new HashMap<>();
    String certDN = userCertificate.getSubjectDN().getName();
    X500Name x500name = new X500Name(certDN);
    logger.warn("Parsed certificate, DN: " + certDN);
    String fullname = getElement(x500name, BCStyle.CN);
    user.put("fullname", fullname);
    String combinedOrg = getElement(x500name, BCStyle.O);
    user.put("email", getElement(x500name, BCStyle.EmailAddress));
    // Extract first and last name from full name
    String lastName = "";
    String firstName = "";
    if (fullname.split("\\w+").length > 1) {
        lastName = fullname.substring(fullname.lastIndexOf(" ") + 1);
        firstName = fullname.substring(0, fullname.lastIndexOf(' '));
    } else {// w w  w  . j  ava2 s .c o  m
        firstName = fullname;
    }
    user.put("lastName", lastName);
    user.put("firstName", firstName);
    String[] orgNames = combinedOrg.split(";");
    String orgShortName = orgNames[0].toLowerCase();
    user.put("orgShortName", orgShortName);
    user.put("orgFullName", orgNames[1]);
    // prefix orgUserName with org shortname if not already done
    String orgUserName = getElement(x500name, BCStyle.UID).toLowerCase();
    if (!orgUserName.startsWith(orgShortName + ".")) {
        orgUserName = orgShortName.toLowerCase() + "." + orgUserName;
    }
    user.put("orgUserName", orgUserName);
    user.put("type", getElement(x500name, BCStyle.OU));
    // Extract info from Subject Alternative Name extension
    Collection<List<?>> san = null;
    try {
        san = userCertificate.getSubjectAlternativeNames();
    } catch (CertificateParsingException e) {
        logger.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
        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) {
                    logger.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } catch (Exception e) {
                    logger.error("Error decoding subjectAltName" + e.getLocalizedMessage(), e);
                    continue;
                } finally {
                    if (decoder != null) {
                        try {
                            decoder.close();
                        } catch (IOException e) {
                        }
                    }
                }
                logger.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:
                    logger.debug("Ship specific OIDs are ignored");
                    break;
                case MC_OID_MRN:
                    // We only support 1 mrn
                    user.put("mrn", value);
                    break;
                case MC_OID_PERMISSIONS:
                    user.put("permissions", value);
                    break;
                default:
                    logger.error("Unknown OID!");
                    break;
                }
            } else {
                // Other types are not supported so ignore them
                logger.warn("SubjectAltName of invalid type found: " + type);
            }
        }
    }
    return user;
}

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);/*from  w  ww  .j  a va2s. co  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.
 *///from w w w .ja  v a  2 s . c o m
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.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/*from  w ww.  j a va 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//  w  w w .j  a va2s  .c  o  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 . j a v a 2 s  .  co m*/
 * @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:org.apache.nifi.registry.security.util.CertificateUtils.java

License:Apache License

private static Map<ASN1ObjectIdentifier, Integer> createDnOrderMap() {
    Map<ASN1ObjectIdentifier, Integer> orderMap = new HashMap<>();
    int count = 0;
    orderMap.put(BCStyle.CN, count++);// w ww .j  a  v a  2 s . c  om
    orderMap.put(BCStyle.L, count++);
    orderMap.put(BCStyle.ST, count++);
    orderMap.put(BCStyle.O, count++);
    orderMap.put(BCStyle.OU, count++);
    orderMap.put(BCStyle.C, count++);
    orderMap.put(BCStyle.STREET, count++);
    orderMap.put(BCStyle.DC, count++);
    orderMap.put(BCStyle.UID, count++);
    return Collections.unmodifiableMap(orderMap);
}