/*
Returns the subject alternative name of the specified type in the
subjectAltNames extension of a certificate.
510406
private static Object getSubjectAltName(X509Certificate cert, int type) {
        Collection<List<?>> subjectAltNames;

        try {
            subjectAltNames = cert.getSubjectAlternativeNames();
        } catch (CertificateParsingException cpe) {
            if (debug != null && Debug.isOn("handshake")) {
                System.out.println(
                        "Attempt to obtain subjectAltNames extension failed!");
            }
            return null;
        }

        if (subjectAltNames != null) {
            for (List<?> subjectAltName : subjectAltNames) {
                int subjectAltNameType = (Integer)subjectAltName.get(0);
                if (subjectAltNameType == type) {
                    return subjectAltName.get(1);
                }
            }
        }

        return null;
    }
968291
protected String getTypeName(JvmType type) {
		if (type != null) {
			if (type instanceof JvmDeclaredType) {
				final ITypeReferenceOwner owner = new StandardTypeReferenceOwner(this.services, type);
				return owner.toLightweightTypeReference(type).getHumanReadableName();
			}
			return type.getSimpleName();
		}
		return Messages.SARLHoverSignatureProvider_1;
	}
499747
def get_subj_alt_name(peer_cert):
    
    # Pass the cert to cryptography, which has much better APIs for this.
    if hasattr(peer_cert, "to_cryptography"):
        cert = peer_cert.to_cryptography()
    else:
        # This is technically using private APIs, but should work across all
        # relevant versions before PyOpenSSL got a proper API for this.
        cert = _Certificate(openssl_backend, peer_cert._x509)

    # We want to find the SAN extension. Ask Cryptography to locate it (it's
    # faster than looping in Python)
    try:
        ext = cert.extensions.get_extension_for_class(
            x509.SubjectAlternativeName
        ).value
    except x509.ExtensionNotFound:
        # No such extension, return the empty list.
        return []
    except (x509.DuplicateExtension, UnsupportedExtension,
            x509.UnsupportedGeneralNameType, UnicodeError) as e:
        # A problem has been found with the quality of the certificate. Assume
        # no SAN field is present.
        log.warning(
            "A problem was encountered with the certificate that prevented "
            "urllib3 from finding the SubjectAlternativeName field. This can "
            "affect certificate validation. The error was %s",
            e,
        )
        return []

    # We want to return dNSName and iPAddress fields. We need to cast the IPs
    # back to strings because the match_hostname function wants them as
    # strings.
    # Sadly the DNS names need to be idna encoded and then, on Python 3, UTF-8
    # decoded. This is pretty frustrating, but that's what the standard library
    # does with certificates, and so we need to attempt to do the same.
    # We also want to skip over names which cannot be idna encoded.
    names = [
        ('DNS', name) for name in map(_dnsname_to_stdlib, ext.get_values_for_type(x509.DNSName))
        if name is not None
    ]
    names.extend(
        ('IP Address', str(name))
        for name in ext.get_values_for_type(x509.IPAddress)
    )

    return names
873504
public static String nameToIdentifier(String name, IdentifierType type) {

        if (null == name || name.length() == 0) {
            return name;
        }

        // algorithm will not change an XML name that is already a legal and
        // conventional (!) Java class, method, or constant identifier

        boolean legalIdentifier = false;
        StringBuilder buf = new StringBuilder(name);
        boolean hasUnderscore = false;
        legalIdentifier = Character.isJavaIdentifierStart(buf.charAt(0));

        for (int i = 1; i < name.length() && legalIdentifier; i++) {
            legalIdentifier &= Character.isJavaIdentifierPart(buf.charAt(i));
            hasUnderscore |= '_' == buf.charAt(i);
        }

        boolean conventionalIdentifier = isConventionalIdentifier(buf, type);
        if (legalIdentifier && conventionalIdentifier) {
            if (JAXBUtils.isJavaKeyword(name) && type == IdentifierType.VARIABLE) {
                name = normalizePackageNamePart(name);
            }
            if (!hasUnderscore || IdentifierType.CLASS != type) {
                return name;
            }
        }

        // split into words

        List<String> words = new ArrayList<>();

        StringTokenizer st = new StringTokenizer(name, XML_NAME_PUNCTUATION_STRING);
        while (st.hasMoreTokens()) {
            words.add(st.nextToken());
        }

        for (int i = 0; i < words.size(); i++) {
            splitWord(words, i);
        }

        return makeConventionalIdentifier(words, type);
    }
90714
protected String getAlternatePrincipal(final X509Certificate certificate) {
        if (alternatePrincipalAttribute == null) {
            return null;
        }
        val attributes = extractPersonAttributes(certificate);
        val attribute = attributes.get(alternatePrincipalAttribute);
        if (attribute == null) {
            LOGGER.debug("Attempt to get alternate principal with attribute [{}] was unsuccessful.", alternatePrincipalAttribute);
            return null;
        }
        val optionalAttribute = CollectionUtils.firstElement(attribute);
        if (optionalAttribute.isEmpty()) {
            LOGGER.debug("Alternate attribute list for [{}] was empty.", alternatePrincipalAttribute);
            return null;
        }
        val alternatePrincipal = optionalAttribute.get().toString();
        if (StringUtils.isNotEmpty(alternatePrincipal)) {
            LOGGER.debug("Using alternate principal attribute [{}]", alternatePrincipal);
            return alternatePrincipal;
        }
        LOGGER.debug("Returning null principal id...");
        return null;
    }
100117
public Object get(String name)
    throws CertificateException, IOException {
        X509AttributeName attrName = new X509AttributeName(name);

        int attr = attributeMap(attrName.getPrefix());
        if (attr == 0) {
            throw new CertificateParsingException(
                          "Attribute name not recognized: " + name);
        }
        String suffix = attrName.getSuffix();

        switch (attr) { // frequently used attributes first
        case (ATTR_EXTENSIONS):
            if (suffix == null) {
                return(extensions);
            } else {
                if (extensions == null) {
                    return null;
                } else {
                    return(extensions.get(suffix));
                }
            }
        case (ATTR_SUBJECT):
            if (suffix == null) {
                return(subject);
            } else {
                return(getX500Name(suffix, false));
            }
        case (ATTR_ISSUER):
            if (suffix == null) {
                return(issuer);
            } else {
                return(getX500Name(suffix, true));
            }
        case (ATTR_KEY):
            if (suffix == null) {
                return(pubKey);
            } else {
                return(pubKey.get(suffix));
            }
        case (ATTR_ALGORITHM):
            if (suffix == null) {
                return(algId);
            } else {
                return(algId.get(suffix));
            }
        case (ATTR_VALIDITY):
            if (suffix == null) {
                return(interval);
            } else {
                return(interval.get(suffix));
            }
        case (ATTR_VERSION):
            if (suffix == null) {
                return(version);
            } else {
                return(version.get(suffix));
            }
        case (ATTR_SERIAL):
            if (suffix == null) {
                return(serialNum);
            } else {
                return(serialNum.get(suffix));
            }
        case (ATTR_ISSUER_ID):
            return(issuerUniqueId);
        case (ATTR_SUBJECT_ID):
            return(subjectUniqueId);
        }
        return null;
    }
157993
private void verifyCert(X500Name subject,
        CertificateExtensions extensions)
        throws CertificateParsingException, IOException {

        // if SubjectName is empty, check for SubjectAlternativeNameExtension
        if (subject.isEmpty()) {
            if (extensions == null) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and certificate " +
                        "has no extensions");
            }
            SubjectAlternativeNameExtension subjectAltNameExt = null;
            SubjectAlternativeNameExtension extValue = null;
            GeneralNames names = null;
            try {
                subjectAltNameExt = (SubjectAlternativeNameExtension)
                        extensions.get(SubjectAlternativeNameExtension.NAME);
                names = subjectAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
            } catch (IOException e) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and " +
                        "SubjectAlternativeName extension is absent");
            }

            // SubjectAlternativeName extension is empty or not marked critical
            if (names == null || names.isEmpty()) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: subject field is empty, and " +
                        "SubjectAlternativeName extension is empty");
            } else if (subjectAltNameExt.isCritical() == false) {
                throw new CertificateParsingException("X.509 Certificate is " +
                        "incomplete: SubjectAlternativeName extension MUST " +
                        "be marked critical when subject field is empty");
            }
        }
    }
980007
public static String getGetterName(String propertyName, Class type) {
        String prefix = type == boolean.class || type == Boolean.class ? "is" : "get";
        return prefix + MetaClassHelper.capitalize(propertyName);
    }
578918
private static String resolveIdentity(ResourceAddress address, Subject subject) {
        IdentityResolver resolver = address.getOption(IDENTITY_RESOLVER);
        ResourceAddress transport = address.getTransport();
        if (resolver != null) {
            return resolver.resolve(subject);
        }
        if (transport != null) {
            return resolveIdentity(transport, subject);
        }
        return null;
    }
1197151
function getSingleCallSignature(type) {
            if (type.flags & 2588672 /* ObjectType */) {
                var resolved = resolveStructuredTypeMembers(type);
                if (resolved.callSignatures.length === 1 && resolved.constructSignatures.length === 0 &&
                    resolved.properties.length === 0 && !resolved.stringIndexInfo && !resolved.numberIndexInfo) {
                    return resolved.callSignatures[0];
                }
            }
            return undefined;
        }
596169
private String getCustSerializedName(FieldOptions options, String defaultName) {
    for (Extension<FieldOptions, String> extension : serializedNameExtensions) {
      if (options.hasExtension(extension)) {
        return options.getExtension(extension);
      }
    }
    return protoFormat.to(jsonFormat, defaultName);
  }
1287283
public static String getProxyTypeAsString(GSIConstants.CertificateType proxyType) {
        switch(proxyType) {
        case GSI_4_IMPERSONATION_PROXY:
            return "RFC 3820 compliant impersonation proxy";
        case GSI_4_INDEPENDENT_PROXY:
            return "RFC 3820 compliant independent proxy";
        case GSI_4_LIMITED_PROXY:
            return "RFC 3820 compliant limited proxy";
        case GSI_4_RESTRICTED_PROXY:
            return "RFC 3820 compliant restricted proxy";
        case GSI_3_IMPERSONATION_PROXY:
            return "Proxy draft compliant impersonation proxy";
        case GSI_3_INDEPENDENT_PROXY:
            return "Proxy draft compliant independent proxy";
        case GSI_3_LIMITED_PROXY:
            return "Proxy draft compliant limited proxy";
        case GSI_3_RESTRICTED_PROXY:
            return "Proxy draft compliant restricted proxy";
        case GSI_2_PROXY:
            return "full legacy globus proxy";
        case GSI_2_LIMITED_PROXY:
            return "limited legacy globus proxy";
        default:
            return "not a proxy";
        }
    }
351680
private static Collection<List<?>> cloneAltNames(Collection<List<?>> altNames) {
        boolean mustClone = false;
        for (List<?> nameEntry : altNames) {
            if (nameEntry.get(1) instanceof byte[]) {
                // must clone names
                mustClone = true;
            }
        }
        if (mustClone) {
            List<List<?>> namesCopy = new ArrayList<>();
            for (List<?> nameEntry : altNames) {
                Object nameObject = nameEntry.get(1);
                if (nameObject instanceof byte[]) {
                    List<Object> nameEntryCopy =
                                        new ArrayList<>(nameEntry);
                    nameEntryCopy.set(1, ((byte[])nameObject).clone());
                    namesCopy.add(Collections.unmodifiableList(nameEntryCopy));
                } else {
                    namesCopy.add(nameEntry);
                }
            }
            return Collections.unmodifiableCollection(namesCopy);
        } else {
            return altNames;
        }
    }

    /**
     * This method are the overridden implementation of
     * getSubjectAlternativeNames method in X509Certificate in the Sun
     * provider. It is better performance-wise since it returns cached
     * values.
     */
    public synchronized Collection<List<?>> getSubjectAlternativeNames()
        throws CertificateParsingException {
        // return cached value if we can
        if (readOnly && subjectAlternativeNames != null)  {
            return cloneAltNames(subjectAlternativeNames);
        }
        SubjectAlternativeNameExtension subjectAltNameExt =
            getSubjectAlternativeNameExtension();
        if (subjectAltNameExt == null) {
            return null;
        }
        GeneralNames names;
        try {
            names = subjectAltNameExt.get(
                    SubjectAlternativeNameExtension.SUBJECT_NAME);
        } catch (IOException ioe) {
            // should not occur
            return Collections.<List<?>>emptySet();
        }
        subjectAlternativeNames = makeAltNames(names);
        return subjectAlternativeNames;
    }

    /**
     * This static method is the default implementation of the
     * getSubjectAlternaitveNames method in X509Certificate. A
     * X509Certificate provider generally should overwrite this to
     * provide among other things caching for better performance.
     */
    public static Collection<List<?>> getSubjectAlternativeNames(X509Certificate cert)
        throws CertificateParsingException {
        try {
            byte[] ext = cert.getExtensionValue(SUBJECT_ALT_NAME_OID);
            if (ext == null) {
                return null;
            }
            DerValue val = new DerValue(ext);
            byte[] data = val.getOctetString();

            SubjectAlternativeNameExtension subjectAltNameExt =
                new SubjectAlternativeNameExtension(Boolean.FALSE,
                                                    data);

            GeneralNames names;
            try {
                names = subjectAltNameExt.get(
                        SubjectAlternativeNameExtension.SUBJECT_NAME);
            }  catch (IOException ioe) {
                // should not occur
                return Collections.<List<?>>emptySet();
            }
            return makeAltNames(names);
        } catch (IOException ioe) {
            throw new CertificateParsingException(ioe);
        }
    }

    /**
     * This method are the overridden implementation of
     * getIssuerAlternativeNames method in X509Certificate in the Sun
     * provider. It is better performance-wise since it returns cached
     * values.
     */
    public synchronized Collection<List<?>> getIssuerAlternativeNames()
        throws CertificateParsingException {
        // return cached value if we can
        if (readOnly && issuerAlternativeNames != null) {
            return cloneAltNames(issuerAlternativeNames);
        }
        IssuerAlternativeNameExtension issuerAltNameExt =
            getIssuerAlternativeNameExtension();
        if (issuerAltNameExt == null) {
            return null;
        }
        GeneralNames names;
        try {
            names = issuerAltNameExt.get(
                    IssuerAlternativeNameExtension.ISSUER_NAME);
        } catch (IOException ioe) {
            // should not occur
            return Collections.<List<?>>emptySet();
        }
        issuerAlternativeNames = makeAltNames(names);
        return issuerAlternativeNames;
    }

    /**
     * This static method is the default implementation of the
     * getIssuerAlternaitveNames method in X509Certificate. A
     * X509Certificate provider generally should overwrite this to
     * provide among other things caching for better performance.
     */
    public static Collection<List<?>> getIssuerAlternativeNames(X509Certificate cert)
        throws CertificateParsingException {
        try {
            byte[] ext = cert.getExtensionValue(ISSUER_ALT_NAME_OID);
            if (ext == null) {
                return null;
            }

            DerValue val = new DerValue(ext);
            byte[] data = val.getOctetString();

            IssuerAlternativeNameExtension issuerAltNameExt =
                new IssuerAlternativeNameExtension(Boolean.FALSE,
                                                    data);
            GeneralNames names;
            try {
                names = issuerAltNameExt.get(
                        IssuerAlternativeNameExtension.ISSUER_NAME);
            }  catch (IOException ioe) {
                // should not occur
                return Collections.<List<?>>emptySet();
            }
            return makeAltNames(names);
        } catch (IOException ioe) {
            throw new CertificateParsingException(ioe);
        }
    }

    public AuthorityInfoAccessExtension getAuthorityInfoAccessExtension() {
        return (AuthorityInfoAccessExtension)
            getExtension(PKIXExtensions.AuthInfoAccess_Id);
    }

    /************************************************************/

    /*
     * Cert is a SIGNED ASN.1 macro, a three elment sequence:
     *
     *  - Data to be signed (ToBeSigned) -- the "raw" cert
     *  - Signature algorithm (SigAlgId)
     *  - The signature bits
     *
     * This routine unmarshals the certificate, saving the signature
     * parts away for later verification.
     */
    private void parse(DerValue val)
    throws CertificateException, IOException {
        parse(
            val,
            null // use re-encoded form of val as the encoded form
            );
    }

    /*
     * Cert is a SIGNED ASN.1 macro, a three elment sequence:
     *
     *  - Data to be signed (ToBeSigned) -- the "raw" cert
     *  - Signature algorithm (SigAlgId)
     *  - The signature bits
     *
     * This routine unmarshals the certificate, saving the signature
     * parts away for later verification.
     */
    private void parse(DerValue val, byte[] originalEncodedForm)
    throws CertificateException, IOException {
        // check if can over write the certificate
        if (readOnly)
            throw new CertificateParsingException(
                      "cannot over-write existing certificate");

        if (val.data == null || val.tag != DerValue.tag_Sequence)
            throw new CertificateParsingException(
                      "invalid DER-encoded certificate data");

        signedCert =
                (originalEncodedForm != null)
                        ? originalEncodedForm : val.toByteArray();
        DerValue[] seq = new DerValue[3];

        seq[0] = val.data.getDerValue();
        seq[1] = val.data.getDerValue();
        seq[2] = val.data.getDerValue();

        if (val.data.available() != 0) {
            throw new CertificateParsingException("signed overrun, bytes = "
                                     + val.data.available());
        }
        if (seq[0].tag != DerValue.tag_Sequence) {
            throw new CertificateParsingException("signed fields invalid");
        }

        algId = AlgorithmId.parse(seq[1]);
        signature = seq[2].getBitString();

        if (seq[1].data.available() != 0) {
            throw new CertificateParsingException("algid field overrun");
        }
        if (seq[2].data.available() != 0)
            throw new CertificateParsingException("signed fields overrun");

        // The CertificateInfo
        info = new X509CertInfo(seq[0]);

        // the "inner" and "outer" signature algorithms must match
        AlgorithmId infoSigAlg = (AlgorithmId)info.get(
                                              CertificateAlgorithmId.NAME
                                              + DOT +
                                              CertificateAlgorithmId.ALGORITHM);
        if (! algId.equals(infoSigAlg))
            throw new CertificateException("Signature algorithm mismatch");
        readOnly = true;
    }
456928
public boolean isValidSubject(X500Principal subject) {

        if (subject == null) {
            throw new IllegalArgumentException();
        }

        String subjectDN = CertificateUtil.toGlobusID(subject);

        if ((this.allowedDNs == null) || (this.allowedDNs.size() < 1)) {
            return false;
        }

        int size = this.allowedDNs.size();
        for (int i = 0; i < size; i++) {
            Pattern pattern = allowedDNs.get(i);
            Matcher matcher = pattern.matcher(subjectDN);
            boolean valid = matcher.matches();
            if (valid) {
                return true;
            }
        }

        return false;
    }
168135
protected String findCertInfo(X509Certificate[] x509certificates) throws NamingException {
        if (x509certificates != null && x509certificates.length != 0) {
            // Only ever use the first certificate, as this si the client supplied one.
            // Further ones are trust stores and CAs that have signed the first cert.
            Principal subject = x509certificates[0].getSubjectDN();
            if (subject != null && subject.getName() != null) {
                List<Rdn> rdns;
                try {
                    rdns = new LdapName(subject.getName()).getRdns();
                }
                catch (InvalidNameException ine) {
                    return null;
                }
                return certInfoExtractor.extractCertInfo(rdns);
            }
        }
        return null;
    }
796986
def get_common_name(cls, csr):
        
        from tempfile import NamedTemporaryFile
        fhandle = NamedTemporaryFile()
        fhandle.write(csr.encode('latin1'))
        fhandle.flush()
        output = cls.exec_output('openssl req -noout -subject -in %s' %
                                 fhandle.name)
        if not output:
            return

        common_name = output.split('=')[-1].strip()
        fhandle.close()
        return common_name
169726
def _get_subject_alternative_names(self, ext):
        
        values = []
        for san in ext.value:
            if isinstance(san.value, string):
                # Pass on simple string SAN values
                values.append(san.value)
            elif isinstance(san.value, x509.Name):
                # In theory there there could be >1 RDN here...
                values.extend(
                    self._name_attribute_to_string(rdn) for rdn in san.value.rdns
                )
        return values