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

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

Introduction

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

Prototype

public RDN[] getRDNs(ASN1ObjectIdentifier attributeType) 

Source Link

Document

return an array of RDNs containing the attribute type given by OID in structure order.

Usage

From source file:org.digidoc4j.impl.bdoc.xades.TimemarkSignature.java

License:GNU General Public License

private String getCN(X500Name x500Name) {
    RDN[] rdNs = x500Name.getRDNs(new ASN1ObjectIdentifier("2.5.4.3"));
    if (rdNs == null || rdNs.length == 0) {
        return null;
    }/* ww  w  .ja va  2  s .c  o  m*/
    AttributeTypeAndValue[] typesAndValues = rdNs[0].getTypesAndValues();
    if (typesAndValues == null || typesAndValues.length == 0) {
        return null;
    }
    String name = typesAndValues[0].getValue().toString();
    return name;
}

From source file:org.eclipse.andmore.android.certmanager.ui.dialogs.CertificateInfoDialog.java

License:Apache License

@Override
protected Control createDialogArea(Composite parent) {
    Composite newComposite = (Composite) super.createDialogArea(parent);
    X509Certificate cert = null;/*from   w  w w .ja v a  2 s.  co m*/

    try {
        cert = entry.getX509Certificate();

        if (cert != null) {
            X500Name x500name = new JcaX509CertificateHolder(cert).getSubject();
            RDN commonName = x500name.getRDNs(BCStyle.CN).length >= 1 ? x500name.getRDNs(BCStyle.CN)[0] : null;
            RDN organization = x500name.getRDNs(BCStyle.O).length >= 1 ? x500name.getRDNs(BCStyle.O)[0] : null;
            RDN organizationUnit = x500name.getRDNs(BCStyle.OU).length >= 1 ? x500name.getRDNs(BCStyle.OU)[0]
                    : null;
            RDN country = x500name.getRDNs(BCStyle.C).length >= 1 ? x500name.getRDNs(BCStyle.C)[0] : null;
            RDN state = x500name.getRDNs(BCStyle.ST).length >= 1 ? x500name.getRDNs(BCStyle.ST)[0] : null;
            RDN locality = x500name.getRDNs(BCStyle.L).length >= 1 ? x500name.getRDNs(BCStyle.L)[0] : null;

            block.createInfoBlock(newComposite, entry.getAlias(), printCertInfo(commonName),
                    printCertInfo(organization), printCertInfo(organizationUnit), printCertInfo(country),
                    printCertInfo(state), printCertInfo(locality), cert.getNotAfter(), cert.getNotBefore());
        } else {
            // not found Android certificate expected (X509Certificate)
            EclipseUtils.showErrorDialog(
                    CertificateManagerNLS.CertificateInfoDialog_UnknownCertificateKeypairType,
                    CertificateManagerNLS.CertificatePropertiesHandler_ErrorGettingCertificateOrKeypairProperties);
        }
    } catch (Exception e) {
        EclipseUtils.showErrorDialog(
                CertificateManagerNLS.CertificatePropertiesHandler_ErrorGettingCertificateOrKeypairProperties,
                e.getMessage());
        AndmoreLogger.error(CertificateInfoDialog.class,
                CertificateManagerNLS.CertificatePropertiesHandler_ErrorGettingCertificateOrKeypairProperties,
                e);
    }
    return newComposite;
}

From source file:org.eclipse.andmore.android.certmanager.ui.model.EntryNode.java

License:Apache License

/**
 * // ww  w  . jav a  2s.  c o m
 * @param keyStoreModel
 * @param alias
 * @throws KeyStoreManagerException
 *             if the alias is already listed in the tree
 */
public EntryNode(ITreeNode keyStoreModel, String alias) throws KeyStoreManagerException {
    this.alias = alias.toLowerCase();
    setParent(keyStoreModel);
    if (!isKeyPairEntry()) {
        keyStoreModel.addChild(this);
    }

    // notify key entry addition
    // KeyStoreModelEventManager.getInstance().fireEvent(this,
    // KeyStoreModelEvent.EventType.ADD);

    // Obtaining certificate to get tooltip information
    X509Certificate cert = getX509Certificate();
    if (cert != null) {
        X500Name x500name;
        try {
            x500name = new JcaX509CertificateHolder(cert).getSubject();

            RDN commonName = x500name.getRDNs(BCStyle.CN).length >= 1 ? x500name.getRDNs(BCStyle.CN)[0] : null;
            RDN organization = x500name.getRDNs(BCStyle.O).length >= 1 ? x500name.getRDNs(BCStyle.O)[0] : null;

            // Adding tooltip information
            String org = organization != null ? organization.getFirst().getValue().toString()
                    : CertificateManagerNLS.CertificateInfoDialog_NotAvailableProperty;
            String name = commonName != null ? commonName.getFirst().getValue().toString()
                    : CertificateManagerNLS.CertificateInfoDialog_NotAvailableProperty;
            this.setTooltip(NLS.bind(CertificateManagerNLS.CertificateBlock_KeyTooltip, org, name));
        } catch (CertificateEncodingException e) {
            String errorMsg = "Error getting data from certificate";
            AndmoreLogger.error(EntryNode.class, errorMsg, e);
            throw new KeyStoreManagerException(errorMsg, e);
        }
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpRAUnidTest.java

License:Open Source License

@Override
protected void checkDN(X500Name expected, X500Name actual) {
    final ASN1ObjectIdentifier[] expectedOIDs = expected.getAttributeTypes();
    final ASN1ObjectIdentifier[] actualOIDs = actual.getAttributeTypes();
    assertEquals("Not the expected number of elements in the created certificate.", expectedOIDs.length,
            actualOIDs.length);/*  w  w w .  ja  v a  2s . co m*/
    String expectedValue, actualValue;
    for (int i = 0; i < expectedOIDs.length; i++) {
        final ASN1ObjectIdentifier oid = expectedOIDs[i];
        expectedValue = expected.getRDNs(oid)[0].getFirst().getValue().toString();
        actualValue = actual.getRDNs(oid)[0].getFirst().getValue().toString();
        if (!oid.equals(BCStyle.SN)) {
            log.debug("Check that " + oid.getId() + " is OK. Expected '" + expectedValue + "'. Actual '"
                    + actualValue + "'.");
            assertEquals("Not expected " + oid, expectedValue, actualValue);
            continue;
        }
        log.debug("Special handling of the SN " + oid.getId() + ". Input '" + expectedValue + "'. Transformed '"
                + actualValue + "'.");
        final String expectedSNPrefix = UNIDPREFIX + LRA;
        final String actualSNPrefix = actualValue.substring(0, expectedSNPrefix.length());
        assertEquals("New serial number prefix not as expected.", expectedSNPrefix, actualSNPrefix);
        final String actualSNRandom = actualValue.substring(expectedSNPrefix.length());
        assertTrue("Random in serial number not OK: " + actualSNRandom,
                Pattern.compile("^\\w{6}$").matcher(actualSNRandom).matches());
    }
}

From source file:org.ejbca.core.protocol.cmp.CmpRAUnidTest.java

License:Open Source License

private void doTest(Connection dbConn) throws Exception {

    final byte[] nonce = CmpMessageHelper.createSenderNonce();
    final byte[] transid = CmpMessageHelper.createSenderNonce();
    final int reqId;
    final String unid;
    {/* w w w . j a va 2s .  c o  m*/
        // In this test SUBJECT_DN contains special, escaped characters to verify
        // that that works with CMP RA as well
        final PKIMessage one = genCertReq(CmpRAUnidTest.issuerDN, SUBJECT_DN, this.keys, this.cacert, nonce,
                transid, true, null, null, null, null, null, null);
        final PKIMessage req = protectPKIMessage(one, false, PBEPASSWORD, CPNAME, 567);
        assertNotNull(req);

        CertReqMessages ir = (CertReqMessages) req.getBody().getContent();
        reqId = ir.toCertReqMsgArray()[0].getCertReq().getCertReqId().getValue().intValue();
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, configAlias);

        ASN1InputStream inputStream = new ASN1InputStream(new ByteArrayInputStream(resp));
        try {
            PKIMessage respObject = PKIMessage.getInstance(inputStream.readObject());
            PKIBody body = respObject.getBody();
            if (body.getContent() instanceof ErrorMsgContent) {
                ErrorMsgContent err = (ErrorMsgContent) body.getContent();
                String errMsg = err.getPKIStatusInfo().getStatusString().getStringAt(0).getString();
                log.error(errMsg);
                fail("CMP ErrorMsg received: " + errMsg);
                unid = null;
            } else {
                checkCmpResponseGeneral(resp, CmpRAUnidTest.issuerDN, SUBJECT_DN, this.cacert, nonce, transid,
                        false, PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
                final X509Certificate cert = checkCmpCertRepMessage(SUBJECT_DN, this.cacert, resp, reqId);
                final X500Name name = X500Name.getInstance(cert.getSubjectX500Principal().getEncoded());
                unid = IETFUtils.valueToString(name.getRDNs(BCStyle.SN)[0].getFirst().getValue());
                log.debug("Unid received in certificate response: " + unid);
            }
        } finally {
            inputStream.close();
        }
    }
    {
        final PreparedStatement ps = dbConn.prepareStatement("select fnr from UnidFnrMapping where unid=?");
        ps.setString(1, unid);
        final ResultSet result = ps.executeQuery();
        assertTrue("Unid '" + unid + "' not found in DB.", result.next());
        final String fnr = result.getString(1);
        result.close();
        ps.close();
        log.debug("FNR read from DB: " + fnr);
        assertEquals("Right FNR not found in DB.", FNR, fnr);
    }
    {
        // Send a confirm message to the CA
        final String hash = "foo123";
        final PKIMessage confirm = genCertConfirm(SUBJECT_DN, this.cacert, nonce, transid, hash, reqId);
        assertNotNull(confirm);
        final PKIMessage req1 = protectPKIMessage(confirm, false, PBEPASSWORD, CPNAME, 567);
        final ByteArrayOutputStream bao = new ByteArrayOutputStream();
        final DEROutputStream out = new DEROutputStream(bao);
        out.writeObject(req1);
        final byte[] ba = bao.toByteArray();
        // Send request and receive response
        final byte[] resp = sendCmpHttp(ba, 200, configAlias);
        checkCmpResponseGeneral(resp, CmpRAUnidTest.issuerDN, SUBJECT_DN, this.cacert, nonce, transid, false,
                PBEPASSWORD, PKCSObjectIdentifiers.sha1WithRSAEncryption.getId());
        checkCmpPKIConfirmMessage(SUBJECT_DN, this.cacert, resp);
    }
}

From source file:org.ejbca.core.protocol.unid.UnidFnrHandler.java

License:Open Source License

@Override
public RequestMessage processRequestMessage(RequestMessage req, String certificateProfileName,
        String unidDataSource) throws HandlerException {

    if (this.storage == null) {
        this.storage = new MyStorage(unidDataSource);
    }//from  www .  j a v a 2s  .  c  o  m

    final X500Name dn = req.getRequestX500Name();
    if (LOG.isDebugEnabled()) {
        LOG.debug(">processRequestMessage:'" + dn + "' and '" + certificateProfileName + "'");
    }
    final String unidPrefix = getPrefixFromCertProfileName(certificateProfileName);
    if (unidPrefix == null) {
        return req;
    }
    final ASN1ObjectIdentifier[] oids = dn.getAttributeTypes();
    X500NameBuilder nameBuilder = new X500NameBuilder(new CeSecoreNameStyle());
    boolean changed = false;
    for (int i = 0; i < oids.length; i++) {
        if (oids[i].equals(CeSecoreNameStyle.SERIALNUMBER)) {
            RDN[] rdns = dn.getRDNs(oids[i]);
            String value = rdns[0].getFirst().getValue().toString();
            final String newSerial = storeUnidFrnAndGetNewSerialNr(value, unidPrefix);
            if (newSerial != null) {
                nameBuilder.addRDN(oids[i], newSerial);
                changed = true;
            }
        } else {
            nameBuilder.addRDN(dn.getRDNs(oids[i])[0].getFirst());
        }
    }
    if (changed) {
        req = new RequestMessageSubjectDnAdapter(req, nameBuilder.build());
    }
    return req;
}

From source file:org.forgerock.openidm.security.impl.SecurityResourceProvider.java

License:Open Source License

/**
 * Adds an attribute to an issuer map object if it exists in the supplied X500Name object.
 * /*  ww  w.j a  v  a  2 s .  c o m*/
 * @param issuer The issuer to add to
 * @param name The X500Name object
 * @param attribute the name of the attribute
 * @param oid the ASN1ObjectIdentifier corresponding to the attribute
 * @throws Exception
 */
private void addAttributeToIssuer(Map<String, Object> issuer, X500Name name, String attribute,
        ASN1ObjectIdentifier oid) throws Exception {
    RDN[] rdns = name.getRDNs(oid);
    if (rdns != null && rdns.length > 0) {
        issuer.put(attribute, rdns[0].getFirst().getValue().toString());
    }
}

From source file:org.hyperledger.fabric.sdk.Endpoint.java

License:Open Source License

Endpoint(String url, Properties properties) {

    logger.trace(String.format("Creating endpoint for url %s", url));
    this.url = url;

    String pem = null;//from  w  w  w .  ja  va  2  s  . c om
    String cn = null;
    String sslp = null;
    String nt = null;

    Properties purl = parseGrpcUrl(url);
    String protocol = purl.getProperty("protocol");
    this.addr = purl.getProperty("host");
    this.port = Integer.parseInt(purl.getProperty("port"));

    if (properties != null) {
        if ("grpcs".equals(protocol)) {
            try {
                pem = properties.getProperty("pemFile");
                cn = properties.getProperty("hostnameOverride");

                if (cn == null && "true".equals(properties.getProperty("trustServerCertificate"))) {

                    File pemF = new File(pem);
                    final String cnKey = pemF.getAbsolutePath() + pemF.length() + pemF.lastModified();

                    cn = cnCache.get(cnKey);
                    if (cn == null) {
                        Path path = Paths.get(pem);
                        byte[] data = Files.readAllBytes(path);

                        CryptoPrimitives cp = new CryptoPrimitives();

                        X500Name x500name = new JcaX509CertificateHolder(
                                (X509Certificate) cp.bytesToCertificate(data)).getSubject();
                        RDN rdn = x500name.getRDNs(BCStyle.CN)[0];
                        //   cnn =  cn +"";
                        AttributeTypeAndValue f = rdn.getFirst();
                        cn = IETFUtils.valueToString(rdn.getFirst().getValue());
                        cnCache.put(cnKey, cn);
                    }

                }
            } catch (Exception e) {
                /// Mostly a development env. just log it.
                logger.error(
                        "Error getting Subject CN from certificate. Try setting it specifically with hostnameOverride property. "
                                + e.getMessage());

            }

            sslp = properties.getProperty("sslProvider");
            if (sslp == null) {
                throw new RuntimeException("Property of sslProvider expected");
            }
            if (!sslp.equals("openSSL") && !sslp.equals("JDK")) {
                throw new RuntimeException("Property of sslProvider has to be either openSSL or JDK");
            }

            nt = properties.getProperty("negotiationType");
            if (nt == null) {
                throw new RuntimeException("Property of negotiationType expected");
            }
            if (!nt.equals("TLS") && !sslp.equals("plainText")) {
                throw new RuntimeException("Property of negotiationType has to be either TLS or plainText");
            }
        }

    }

    try {
        if (protocol.equalsIgnoreCase("grpc")) {
            this.channelBuilder = ManagedChannelBuilder.forAddress(addr, port).usePlaintext(true);
            addNettyBuilderProps(channelBuilder, properties);
        } else if (protocol.equalsIgnoreCase("grpcs")) {
            if (Utils.isNullOrEmpty(pem)) {
                // use root certificate
                this.channelBuilder = ManagedChannelBuilder.forAddress(addr, port);
                addNettyBuilderProps(channelBuilder, properties);
            } else {
                try {

                    SslProvider sslprovider = sslp.equals("openSSL") ? SslProvider.OPENSSL : SslProvider.JDK;
                    NegotiationType ntype = nt.equals("TLS") ? NegotiationType.TLS : NegotiationType.PLAINTEXT;

                    SslContext sslContext = GrpcSslContexts.forClient().trustManager(new File(pem))
                            .sslProvider(sslprovider).build();
                    this.channelBuilder = NettyChannelBuilder.forAddress(addr, port).sslContext(sslContext)
                            .negotiationType(ntype);
                    if (cn != null) {
                        channelBuilder.overrideAuthority(cn);
                    }
                    addNettyBuilderProps(channelBuilder, properties);
                } catch (SSLException sslex) {
                    throw new RuntimeException(sslex);
                }
            }
        } else {
            throw new RuntimeException("invalid protocol: " + protocol);
        }
    } catch (RuntimeException e) {
        logger.error(e);
        throw e;
    } catch (Exception e) {
        logger.error(e);
        throw new RuntimeException(e);
    }

}

From source file:org.icepdf.ri.common.utility.signatures.SignatureUtilities.java

License:Apache License

/**
 * Parse out a known data element from an X500Name.
 *
 * @param rdName     name to parse value from.
 * @param commonCode BCStyle name ./*from   w ww. j a va 2 s  . c o  m*/
 * @return BCStyle name value,  null if the BCStyle name was not found.
 */
public static String parseRelativeDistinguishedName(X500Name rdName, ASN1ObjectIdentifier commonCode) {
    RDN[] rdns = rdName.getRDNs(commonCode);
    if (rdns != null && rdns.length > 0 && rdns[0].getFirst() != null) {
        return rdns[0].getFirst().getValue().toString();
    }
    return null;
}

From source file:org.jcryptool.visual.jctca.listeners.UserShowCertsListener.java

License:Open Source License

@Override
public void widgetSelected(SelectionEvent e) {
    List lst = (List) e.getSource();
    int selected = lst.getSelectionIndex();
    KeyStoreAlias ksAlias = (KeyStoreAlias) lst.getData(Integer.toString(selected));
    // get public key for the ksAlias and cast it to a X509 Certificate
    X509Certificate pubKey = null;
    try {/*from  w w  w  .  j ava  2 s . c  om*/
        pubKey = (X509Certificate) KeyStoreManager.getInstance().getCertificate(ksAlias);
    } catch (UnrecoverableEntryException e1) {
        LogUtil.logError(e1);
    } catch (NoSuchAlgorithmException e1) {
        LogUtil.logError(e1);
    }
    // create X500Name from the X509 certificate Subjects distinguished name
    X500Name x500name = new X500Name(pubKey.getSubjectX500Principal().toString());
    // I don't know what this next line does exactly, it just works
    RDN rdn = x500name.getRDNs(BCStyle.CN)[0];
    lbl_value_common.setText(rdn.getFirst().getValue().toString());

    lbl_value_org.setText(Messages.UserShowCertsListener_not_part_of_cert);
    lbl_value_orgUnit.setText(Messages.UserShowCertsListener_not_part_of_cert);

    rdn = x500name.getRDNs(BCStyle.L)[0];
    lbl_value_city.setText(rdn.getFirst().getValue().toString());

    rdn = x500name.getRDNs(BCStyle.C)[0];
    lbl_value_country.setText(rdn.getFirst().getValue().toString());
    rdn = x500name.getRDNs(BCStyle.E)[0];
    lbl_value_mail.setText(rdn.getFirst().getValue().toString());

    x500name = new X500Name(pubKey.getIssuerDN().toString());
    rdn = x500name.getRDNs(BCStyle.CN)[0];
    lbl_value_common_by.setText(rdn.getFirst().getValue().toString());
    rdn = x500name.getRDNs(BCStyle.O)[0];
    lbl_value_org_by.setText(rdn.getFirst().getValue().toString());
    rdn = x500name.getRDNs(BCStyle.OU)[0];
    lbl_value_orgUnit_by.setText(rdn.getFirst().getValue().toString());

    lbl_value_issued_on.setText(pubKey.getNotBefore().toString());
    lbl_value_expired_on.setText(pubKey.getNotAfter().toString());

    btn_revoke.setData("selected", ksAlias); //$NON-NLS-1$
    if (Util.isCertificateRevoked(pubKey.getSerialNumber())) {
        btn_revoke.setEnabled(false);
        btn_revoke.setText(Messages.UserShowCertsListener_btn_revoke_cert_was_revoked);
    } else {
        btn_revoke.setEnabled(true);
        btn_revoke.setText(Messages.UserShowCertsListener_btn_revoke_cert);
    }
    lbl_value_common.getParent().layout();
}