Example usage for org.bouncycastle.asn1.x500 AttributeTypeAndValue getType

List of usage examples for org.bouncycastle.asn1.x500 AttributeTypeAndValue getType

Introduction

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

Prototype

public ASN1ObjectIdentifier getType() 

Source Link

Usage

From source file:ca.trustpoint.m2m.M2mTrustAnchor.java

License:Apache License

/**
 * Creates a new instance./*ww  w.  ja  v  a2  s. c  om*/
 *
 * @param x509Certificate X.509 certificate to use as trust anchor.
 * @throws IllegalArgumentException if x509Certificate is null.
 */
public M2mTrustAnchor(X509Certificate x509Certificate) throws IllegalArgumentException {
    if (x509Certificate == null) {
        throw new IllegalArgumentException("x509Certificate cannot be null.");
    }

    X500Name x500Name = JcaX500NameUtil.getSubject(x509Certificate);
    EntityName caName = new EntityName();
    int attributeCount = 0;

    for (RDN rdn : x500Name.getRDNs()) {
        AttributeTypeAndValue attr = rdn.getFirst();
        EntityNameAttributeId attributeId;

        if (BCStyle.C.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.Country;
        } else if (BCStyle.O.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.Organization;
        } else if (BCStyle.OU.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.OrganizationalUnit;
        } else if (BCStyle.DN_QUALIFIER.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.DistinguishedNameQualifier;
        } else if (BCStyle.ST.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.StateOrProvince;
        } else if (BCStyle.L.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.Locality;
        } else if (BCStyle.CN.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.CommonName;
        } else if (BCStyle.SN.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.SerialNumber;
        } else if (BCStyle.DC.equals(attr.getType())) {
            attributeId = EntityNameAttributeId.DomainComponent;
        } else {
            // Unsupported attribute.
            continue;
        }

        caName.addAttribute(new EntityNameAttribute(attributeId, IETFUtils.valueToString(attr.getValue())));
        attributeCount++;

        if (attributeCount == EntityName.MAXIMUM_ATTRIBUTES) {
            // We have reached the maximum number of attributes for an EntityName, so stop here.
            break;
        }
    }

    this.caName = caName;
    this.publicKey = x509Certificate.getPublicKey();
    certificate = null;
}

From source file:com.foilen.smalltools.crypt.bouncycastle.cert.RSACertificate.java

License:Open Source License

/**
 * Get the first certificate's common name.
 *
 * @return the common name/* w  ww  . j a  v a 2s  .c o m*/
 */
public String getCommonName() {
    AssertTools.assertNotNull(certificateHolder, "The certificate is not set");
    X500Name subject = certificateHolder.getSubject();
    for (RDN rdn : subject.getRDNs()) {
        AttributeTypeAndValue first = rdn.getFirst();
        if (OID_COMMON_NAME.equals(first.getType().toString())) {
            return first.getValue().toString();
        }
    }
    return null;
}

From source file:com.foilen.smalltools.crypt.bouncycastle.cert.RSACertificate.java

License:Open Source License

/**
 * Get the certificate's common names.//from w w  w.ja  v  a2s.c o  m
 *
 * @return the common names
 */
public Set<String> getCommonNames() {
    AssertTools.assertNotNull(certificateHolder, "The certificate is not set");
    X500Name subject = certificateHolder.getSubject();
    Set<String> commonNames = new HashSet<>();
    for (RDN rdn : subject.getRDNs()) {
        ASN1Primitive primitive = rdn.toASN1Primitive();
        if (primitive instanceof ASN1Set) {
            ASN1Set asn1Set = (ASN1Set) primitive;
            for (int i = 0; i < asn1Set.size(); ++i) {
                AttributeTypeAndValue next = AttributeTypeAndValue.getInstance(asn1Set.getObjectAt(i));
                if (OID_COMMON_NAME.equals(next.getType().toString())) {
                    commonNames.add(next.getValue().toString());
                }
            }
        }
    }
    return commonNames;
}

From source file:com.google.bitcoin.protocols.payments.PaymentSession.java

License:Apache License

/**
 * Uses the provided PKI method to find the corresponding public key and verify the provided signature.
 * Returns null if no PKI method was specified in the {@link Protos.PaymentRequest}.
 *///from ww  w .j a v  a  2  s  .  c om
public @Nullable PkiVerificationData verifyPki() throws PaymentRequestException {
    try {
        if (pkiVerificationData != null)
            return pkiVerificationData;
        if (paymentRequest.getPkiType().equals("none"))
            // Nothing to verify. Everything is fine. Move along.
            return null;

        String algorithm;
        if (paymentRequest.getPkiType().equals("x509+sha256"))
            algorithm = "SHA256withRSA";
        else if (paymentRequest.getPkiType().equals("x509+sha1"))
            algorithm = "SHA1withRSA";
        else
            throw new PaymentRequestException.InvalidPkiType(
                    "Unsupported PKI type: " + paymentRequest.getPkiType());

        Protos.X509Certificates protoCerts = Protos.X509Certificates.parseFrom(paymentRequest.getPkiData());
        if (protoCerts.getCertificateCount() == 0)
            throw new PaymentRequestException.InvalidPkiData(
                    "No certificates provided in message: server config error");

        // Parse the certs and turn into a certificate chain object. Cert factories can parse both DER and base64.
        // The ordering of certificates is defined by the payment protocol spec to be the same as what the Java
        // crypto API requires - convenient!
        CertificateFactory certificateFactory = CertificateFactory.getInstance("X.509");
        List<X509Certificate> certs = Lists.newArrayList();
        for (ByteString bytes : protoCerts.getCertificateList())
            certs.add((X509Certificate) certificateFactory.generateCertificate(bytes.newInput()));
        CertPath path = certificateFactory.generateCertPath(certs);

        // Retrieves the most-trusted CAs from keystore.
        PKIXParameters params = new PKIXParameters(createKeyStore(trustStorePath));
        // Revocation not supported in the current version.
        params.setRevocationEnabled(false);

        // Now verify the certificate chain is correct and trusted. This let's us get an identity linked pubkey.
        CertPathValidator validator = CertPathValidator.getInstance("PKIX");
        PKIXCertPathValidatorResult result = (PKIXCertPathValidatorResult) validator.validate(path, params);
        PublicKey publicKey = result.getPublicKey();
        // OK, we got an identity, now check it was used to sign this message.
        Signature signature = Signature.getInstance(algorithm);
        // Note that we don't use signature.initVerify(certs.get(0)) here despite it being the most obvious
        // way to set it up, because we don't care about the constraints specified on the certificates: any
        // cert that links a key to a domain name or other identity will do for us.
        signature.initVerify(publicKey);
        Protos.PaymentRequest.Builder reqToCheck = paymentRequest.toBuilder();
        reqToCheck.setSignature(ByteString.EMPTY);
        signature.update(reqToCheck.build().toByteArray());
        if (!signature.verify(paymentRequest.getSignature().toByteArray()))
            throw new PaymentRequestException.PkiVerificationException(
                    "Invalid signature, this payment request is not valid.");

        // Signature verifies, get the names from the identity we just verified for presentation to the user.
        final X509Certificate cert = certs.get(0);
        X500Principal principal = cert.getSubjectX500Principal();
        // At this point the Java crypto API falls flat on its face and dies - there's no clean way to get the
        // different parts of the certificate name except for parsing the string. That's hard because of various
        // custom escaping rules and the usual crap. So, use Bouncy Castle to re-parse the string into binary form
        // again and then look for the names we want. Fail!
        org.bouncycastle.asn1.x500.X500Name name = new X500Name(principal.getName());
        String entityName = null, orgName = null;
        for (RDN rdn : name.getRDNs()) {
            AttributeTypeAndValue pair = rdn.getFirst();
            if (pair.getType().equals(RFC4519Style.cn))
                entityName = ((ASN1String) pair.getValue()).getString();
            else if (pair.getType().equals(RFC4519Style.o))
                orgName = ((ASN1String) pair.getValue()).getString();
        }
        if (entityName == null && orgName == null) {
            // This cert might not be an SSL cert. Just grab the first "subject alt name" if present, e.g. for
            // S/MIME certs.
            final Iterator<List<?>> it = cert.getSubjectAlternativeNames().iterator();
            List<?> list;
            // email addresses have a type code of one.
            if (it.hasNext() && (list = it.next()) != null && (Integer) list.get(0) == 1)
                entityName = (String) list.get(1);
            if (entityName == null)
                throw new PaymentRequestException.PkiVerificationException(
                        "Could not extract name from certificate");
        }
        // Everything is peachy. Return some useful data to the caller.
        PkiVerificationData data = new PkiVerificationData(entityName, orgName, publicKey,
                result.getTrustAnchor());
        // Cache the result so we don't have to re-verify if this method is called again.
        pkiVerificationData = data;
        return data;
    } catch (InvalidProtocolBufferException e) {
        // Data structures are malformed.
        throw new PaymentRequestException.InvalidPkiData(e);
    } catch (CertificateException e) {
        // The X.509 certificate data didn't parse correctly.
        throw new PaymentRequestException.PkiVerificationException(e);
    } catch (NoSuchAlgorithmException e) {
        // Should never happen so don't make users have to think about it. PKIX is always present.
        throw new RuntimeException(e);
    } catch (InvalidAlgorithmParameterException e) {
        throw new RuntimeException(e);
    } catch (CertPathValidatorException e) {
        // The certificate chain isn't known or trusted, probably, the server is using an SSL root we don't
        // know about and the user needs to upgrade to a new version of the software (or import a root cert).
        throw new PaymentRequestException.PkiVerificationException(e);
    } catch (InvalidKeyException e) {
        // Shouldn't happen if the certs verified correctly.
        throw new PaymentRequestException.PkiVerificationException(e);
    } catch (SignatureException e) {
        // Something went wrong during hashing (yes, despite the name, this does not mean the sig was invalid).
        throw new PaymentRequestException.PkiVerificationException(e);
    } catch (IOException e) {
        throw new PaymentRequestException.PkiVerificationException(e);
    } catch (KeyStoreException e) {
        throw new RuntimeException(e);
    }
}

From source file:com.nkapps.billing.services.AuthServiceImpl.java

public Subject extractSubject(CertificateInfoLocal certificateInfo) {
    String tin, name, organization, address, email, role;
    Short ns10Code, ns11Code, kind;

    HashMap<String, String> subjectInfos = new HashMap<>();
    X500Name x500 = new X500Name(certificateInfo.getSubjectName());

    for (RDN rdn : x500.getRDNs()) {
        AttributeTypeAndValue tv = rdn.getFirst();
        String v = tv.getValue().toString().trim().replaceAll("\\s+", " ");
        if (!v.trim().isEmpty())
            subjectInfos.put(BCStyle.INSTANCE.oidToDisplayName(tv.getType()), v);
    }//from   w w w . j  av  a 2 s .c o m
    role = certificateInfo.getRoleName();

    Subject subject = new Subject();
    // set subject datas
    subject.setRole(role);

    return subject;
}

From source file:eu.emi.security.authn.x509.helpers.proxy.ProxyHelper.java

License:Open Source License

public static String getLastCN(X500Name x500Name) throws IllegalArgumentException {
    RDN[] rdns = x500Name.getRDNs();
    if (rdns.length == 0)
        throw new IllegalArgumentException("The DN is empty");
    RDN last = rdns[rdns.length - 1];//from   w ww .  j  a  va 2s.c  o  m

    if (last.isMultiValued())
        throw new IllegalArgumentException("The DN is ended with a multivalued RDN");
    AttributeTypeAndValue cn = last.getFirst();
    if (!cn.getType().equals(BCStyle.CN))
        throw new IllegalArgumentException("The DN is not ended with a CN AVA");

    return IETFUtils.valueToString(cn.getValue());
}

From source file:net.sf.keystore_explorer.crypto.x509.X509CertUtil.java

License:Open Source License

private static String extractCommonName(X500Name name) {
    for (RDN rdn : name.getRDNs()) {
        AttributeTypeAndValue atav = rdn.getFirst();

        if (atav.getType().equals(BCStyle.CN)) {
            return atav.getValue().toString();
        }//from ww  w . ja v  a  2  s .c om
    }

    return null;
}

From source file:net.sf.keystore_explorer.crypto.x509.X509Ext.java

License:Open Source License

private String getDistributionPointNameString(DistributionPointName distributionPointName, String baseIndent)
        throws IOException {
    // @formatter:off

    /*//from   ww  w. j  av a2s.  com
     * DistributionPointName ::= CHOICE { fullname [0] GeneralNames,
     * nameRelativeToCRLIssuer [1] RelativeDistinguishedName }
     *
     * RelativeDistinguishedName ::= SET SIZE (1 .. MAX) OF
     * AttributeTypeAndValue
     *
     * AttributeTypeAndValue ::= ASN1Sequence { type AttributeType, value
     * AttributeValue }
     */

    // @formatter: on

    StringBuilder sb = new StringBuilder();

    sb.append(baseIndent);
    sb.append(res.getString("DistributionPointName"));
    sb.append(NEWLINE);

    if (distributionPointName.getType() == DistributionPointName.FULL_NAME) {
        sb.append(baseIndent);
        sb.append(INDENT);
        sb.append(res.getString("DistributionPointFullName"));
        sb.append(NEWLINE);

        GeneralNames generalNames = GeneralNames.getInstance(distributionPointName.getName());

        for (GeneralName generalName : generalNames.getNames()) {
            sb.append(baseIndent);
            sb.append(INDENT);
            sb.append(INDENT);
            sb.append(GeneralNameUtil.toString(generalName));
            sb.append(NEWLINE);
        }
    } else {
        // DistributionPointName.TAG_NAMERELATIVETOCRLISSUER
        sb.append(baseIndent);
        sb.append(INDENT);
        sb.append(res.getString("DistributionPointNameRelativeToCrlIssuer"));
        sb.append(NEWLINE);

        RDN rdn = RDN.getInstance(distributionPointName.getName());

        for (AttributeTypeAndValue attributeTypeAndValue : rdn.getTypesAndValues()) {
            ASN1ObjectIdentifier attributeType = attributeTypeAndValue.getType();
            ASN1Encodable attributeValue = attributeTypeAndValue.getValue();

            String attributeTypeStr = getAttributeTypeString(attributeType);
            String attributeValueStr = getAttributeValueString(attributeType, attributeValue);

            sb.append(baseIndent);
            sb.append(INDENT);
            sb.append(INDENT);
            sb.append(MessageFormat.format("{0}={1}", attributeTypeStr, attributeValueStr));
            sb.append(NEWLINE);
        }
    }

    return sb.toString();
}

From source file:org.apache.nifi.registry.security.util.CertificateUtils.java

License:Apache License

/**
 * Reorders DN to the order the elements appear in the RFC 2253 table
 *
 * https://www.ietf.org/rfc/rfc2253.txt/*from   w  w w  . j a  v a  2s . c  om*/
 *
 * String  X.500 AttributeType
 * ------------------------------
 * CN      commonName
 * L       localityName
 * ST      stateOrProvinceName
 * O       organizationName
 * OU      organizationalUnitName
 * C       countryName
 * STREET  streetAddress
 * DC      domainComponent
 * UID     userid
 *
 * @param dn a possibly unordered DN
 * @return the ordered dn
 */
public static String reorderDn(String dn) {
    RDN[] rdNs = new X500Name(dn).getRDNs();
    Arrays.sort(rdNs, new Comparator<RDN>() {
        @Override
        public int compare(RDN o1, RDN o2) {
            AttributeTypeAndValue o1First = o1.getFirst();
            AttributeTypeAndValue o2First = o2.getFirst();

            ASN1ObjectIdentifier o1Type = o1First.getType();
            ASN1ObjectIdentifier o2Type = o2First.getType();

            Integer o1Rank = dnOrderMap.get(o1Type);
            Integer o2Rank = dnOrderMap.get(o2Type);
            if (o1Rank == null) {
                if (o2Rank == null) {
                    int idComparison = o1Type.getId().compareTo(o2Type.getId());
                    if (idComparison != 0) {
                        return idComparison;
                    }
                    return String.valueOf(o1Type).compareTo(String.valueOf(o2Type));
                }
                return 1;
            } else if (o2Rank == null) {
                return -1;
            }
            return o1Rank - o2Rank;
        }
    });
    return new X500Name(rdNs).toString();
}

From source file:org.cesecore.certificates.certificate.request.PKCS10RequestMessage.java

License:Open Source License

@Override
public String getUsername() {
    if (username != null) {
        return username;
    }/*from   ww w.  j a v a  2s .  c  o m*/
    // Special if the DN contains unstructuredAddress where it becomes: 
    // CN=pix.primekey.se + unstructuredAddress=pix.primekey.se
    // We only want the CN and not the oid-part.
    // Luckily for us this is handles automatically by BC X500Name class
    X500Name xname = getRequestX500Name();
    String ret = null;
    if (xname == null) {
        log.info("No requestDN in request, probably we could not read/parse/decrypt request.");
    } else {
        RDN[] cnValues = xname.getRDNs(CeSecoreNameStyle.CN);
        if (cnValues.length == 0) {
            log.info("No CN in DN: " + xname.toString());
        } else {
            AttributeTypeAndValue[] tavs = cnValues[0].getTypesAndValues();
            for (AttributeTypeAndValue tav : tavs) {
                if (tav.getType().equals(CeSecoreNameStyle.CN)) {
                    ret = tav.getValue().toString();
                    break;
                }
            }
            // If we have a CN with a normal name like "Test Testsson" we only want to 
            // use the first part as the username
            int index = ret.indexOf(' ');
            if (index > 0) {
                ret = ret.substring(0, index);
            }
        }
    }
    if (log.isDebugEnabled()) {
        log.debug("UserName='" + ret + "'");
    }
    return ret;
}