Extracts the Subject: the final certificate in a chain

@param chain
a normalised chain

@return the subject (the final certificate in the chain)

@throws IllegalArgumentException
if the chain is null or empty
482036
public static X500Principal getSubjectDNFromChain(List<X509Certificate> chain)
	{
		if (chain == null || chain.isEmpty())
			throw new IllegalArgumentException("Must provide a chain that is non-null and non-empty");

		X509Certificate cert = chain.get(chain.size() - 1);

		return cert.getSubjectX500Principal();
	}
1369623
public Certificate []getCertificates(String path)
  {
    if (! isSigned())
      return null;
    
    if (path.length() > 0 && path.charAt(0) == '/')
      path = path.substring(1);

    try {
      if (! getBacking().canRead())
        return null;
      
      JarFile jarFile = getJarFile();
      JarEntry entry;
      InputStream is = null;

      try {
        entry = jarFile.getJarEntry(path);

        if (entry != null) {
          is = jarFile.getInputStream(entry);

          while (is.skip(65536) > 0) {
          }

          is.close();

          return entry.getCertificates();
        }
      } finally {
        closeJarFile(jarFile);
      }
    } catch (IOException e) {
      log.log(Level.FINE, e.toString(), e);

      return null;
    }

    return null;
  }
974509
@Override
	public Certificate[] engineGetCertificateChain(String s) {
		CredentialWrapper credential = getKeyEntry(s);
		X509Certificate[] chain = new X509Certificate[0];
		if (credential != null) {
			try {
				chain = credential.getCredential().getCertificateChain();
			} catch (ResourceStoreException e) {
				logger.warn(e.getMessage(), e);
				chain = null;
			}
		}
		return chain;
	}
1248819
@Override
    public synchronized ChainData removeChain(ChainData chain) throws ChainException {
        String chainName = (null != chain) ? chain.getName() : null;
        String entryMsg = "removeChain: " + chainName;
        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.entry(tc, entryMsg);
        }
        if (null == chain) {
            throw new InvalidChainNameException("Input chain is null");
        }

        // Verify this chain does exist
        if (!chainDataMap.containsKey(chainName)) {
            if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
                // Due to timing windows (i.e. multiple channel providers going away), there is
                // a race to stop and/or clean up chains. This is not a notable condition: the chain can only be removed
                // once.
                Tr.exit(tc, entryMsg, "Chain not found");
            }
            return null;
        }

        removeChainInternal(chain);

        if (TraceComponent.isAnyTracingEnabled() && tc.isEntryEnabled()) {
            Tr.exit(tc, entryMsg);
        }
        return chain;
    }
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;
    }
56167
protected RoleGroup extract(Subject subject) {
        Optional<Principal> match = subject.getPrincipals()
                .stream()
                .filter(g -> g.getName().equals(SecurityConstants.ROLES_IDENTIFIER))
                .findFirst();
        Group rolesGroup = (Group) match.get();
        RoleGroup roles = new SimpleRoleGroup(rolesGroup);
        return roles;
    }
9468
function unbundleCert(bundle) {
  var chain = bundle.trim().split('\n');

  var ca = [];
  var cert = [];

  for (var i = 0, len = chain.length; i < len; i++) {
    var line = chain[i].trim();
    if (!(line.length !== 0)) {
      continue;
    }
    cert.push(line);
    if (line.match(/-END CERTIFICATE-/)) {
      var joined = cert.join('\n');
      ca.push(joined);
      cert = [];
    }
  }
  return ca;
}
17490
public static void verifyChain(List<X509Certificate> chain)
	{
		if (chain == null || chain.isEmpty())
			throw new IllegalArgumentException("Must provide a chain that is non-null and non-empty");

		for (int i = 0; i < chain.size(); i++)
		{
			final X509Certificate certificate = chain.get(i);
			final int issuerIndex = (i != 0) ?
			                        i - 1 :
			                        0; // The index of the issuer is the previous cert (& the root must, of course, sign itself)
			final X509Certificate issuer = chain.get(issuerIndex);

			// Verify the certificate was indeed issued by the previous certificate in the chain
			try
			{
				certificate.verify(issuer.getPublicKey());
			}
			catch (GeneralSecurityException e)
			{
				final String msg = "Failure verifying " + certificate + " against claimed issuer " + issuer;

				throw new IllegalArgumentException(msg + ": " + e.getMessage(), e);
			}
		}
	}
685595
@Override
    public synchronized ChainData getChain(String chainName) {
        ChainData chainData = null;
        // Ensure the input chain name is not null
        if (null != chainName) {
            chainData = this.chainDataMap.get(chainName);
        }
        if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
            Tr.debug(tc, "getChain: " + chainName + " found=" + (null != chainData));
        }
        return chainData;
    }
557536
def _get_client_side_certificate_subject():
    
    subject = django.core.cache.cache.get('client_side_certificate_subject')
    if subject is not None:
        return subject
    cert_pem = _get_client_side_certificate_pem()
    if cert_pem is None:
        return None
    subject = _extract_subject_from_pem(cert_pem)
    django.core.cache.cache.set('client_side_certificate_subject', subject)
    return subject
749873
private List<Certificate> convertToBouncyCastleCertificate(
      X509Certificate[] chain)
  {
    final List<Certificate> bcChain = new ArrayList<>();
    for (X509Certificate cert : chain)
    {
      try
      {
        bcChain.add(Certificate.getInstance(cert.getEncoded()));
      }
      catch (CertificateEncodingException ex)
      {
        throw new RuntimeException("Failed to decode the certificate DER data");
      }
    }
    return bcChain;
  }
475587
def get_subject(self):
        
        assert self.assertion.subject
        subject = self.assertion.subject
        subjconf = []

        if not self.verify_attesting_entity(subject.subject_confirmation):
            raise VerificationError("No valid attesting address")

        for subject_confirmation in subject.subject_confirmation:
            _data = subject_confirmation.subject_confirmation_data

            if subject_confirmation.method == SCM_BEARER:
                if not self._bearer_confirmed(_data):
                    continue
            elif subject_confirmation.method == SCM_HOLDER_OF_KEY:
                if not self._holder_of_key_confirmed(_data):
                    continue
            elif subject_confirmation.method == SCM_SENDER_VOUCHES:
                pass
            else:
                raise ValueError("Unknown subject confirmation method: %s" % (
                    subject_confirmation.method,))

            _recip = _data.recipient
            if not _recip or not self.verify_recipient(_recip):
                raise VerificationError("No valid recipient")

            subjconf.append(subject_confirmation)

        if not subjconf:
            raise VerificationError("No valid subject confirmation")

        subject.subject_confirmation = subjconf

        # The subject may contain a name_id

        if subject.name_id:
            self.name_id = subject.name_id
        elif subject.encrypted_id:
            # decrypt encrypted ID
            _name_id_str = self.sec.decrypt(
                subject.encrypted_id.encrypted_data.to_string())
            _name_id = saml.name_id_from_string(_name_id_str)
            self.name_id = _name_id

        logger.info("Subject NameID: %s", self.name_id)
        return self.name_id
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;
    }
657641
func extractSimpleChain(simpleChain **syscall.CertSimpleChain, count int) (chain []*Certificate, err error) {
	if simpleChain == nil || count == 0 {
		return nil, errors.New("x509: invalid simple chain")
	}

	simpleChains := (*[1 << 20]*syscall.CertSimpleChain)(unsafe.Pointer(simpleChain))[:]
	lastChain := simpleChains[count-1]
	elements := (*[1 << 20]*syscall.CertChainElement)(unsafe.Pointer(lastChain.Elements))[:]
	for i := 0; i < int(lastChain.NumElements); i++ {
		// Copy the buf, since ParseCertificate does not create its own copy.
		cert := elements[i].CertContext
		encodedCert := (*[1 << 20]byte)(unsafe.Pointer(cert.EncodedCert))[:]
		buf := make([]byte, cert.Length)
		copy(buf, encodedCert[:])
		parsedCert, err := ParseCertificate(buf)
		if err != nil {
			return nil, err
		}
		chain = append(chain, parsedCert)
	}

	return chain, nil
}
1322031
public X509CRLEntry getRevokedCertificate(X509Certificate cert) {
        if (revokedMap.isEmpty()) {
            return null;
        }
        X509IssuerSerial issuerSerial = new X509IssuerSerial(cert);
        return revokedMap.get(issuerSerial);
    }
683287
def certclone(chain, copy_extensions=False):

    for i in range(len(chain)):
        chain[i] = chain[i].to_cryptography()

    newchain = []

    '''
    
    '''

    first = True

    for original in chain[::-1]:

        #print(cert)

        key = rsa.generate_private_key(
            public_exponent=65537,
            key_size=2048,
            backend=default_backend()
            )

        key_pem = key.private_bytes(
            encoding=serialization.Encoding.PEM,
            format=serialization.PrivateFormat.TraditionalOpenSSL,
            encryption_algorithm=serialization.NoEncryption()
        ).decode()

        if first:
            print(key_pem)
            first=False

        pubkey = key.public_key()

        # Todo: Code to mimic the private key type of original cert
        # maybe based on pubkey.__class__
        cert = x509.CertificateBuilder()
        cert = cert.subject_name(original.subject)
        cert = cert.issuer_name(original.issuer)
        #cert = cert.serial_number(original.serial_number)
        cert = cert.serial_number(x509.random_serial_number())
        cert = cert.not_valid_before(original.not_valid_before)
        cert = cert.not_valid_after(original.not_valid_after)
        cert = cert.public_key(pubkey)

        if copy_extensions:
            for ext in original.extensions:
                cert = cert.add_extension(ext.value, critical=ext.critical)

        cert = cert.sign(private_key=key, algorithm=original.signature_hash_algorithm, backend=default_backend())
        cert_pem = cert.public_bytes(serialization.Encoding.PEM).decode()
        print(cert_pem)

        newchain.insert(0, cert)
1069174
@Override
    public Response intercept(Interceptor.Chain chain) throws IOException {
        Request newRequest = this.signHeader(chain.request());
        return chain.proceed(newRequest);
    }