Parse the certificate, and return the clientId from the commonName field in subject.
@returns
166965
function getCliendIdFromCert() {
	var x509 = require('x509');
	var certJson = x509.parseCert(fs.readFileSync(process.cwd()+Constant.CERTIFICATE_PATH).toString());
	var cliendId = cert && cert.subject && cert.subject.commonName;

	return clientId;
}
1206044
@Override
    public IdentityToken encodeIdentityToken(Codec codec) {
        IdentityToken token = null;

        SubjectManager subjectManager = new SubjectManager();
        Subject subject = subjectManager.getInvocationSubject();
        if (subject == null) {
            subject = subjectManager.getCallerSubject();
        }

        /*
         * At this point, we have either the invocation subject or the caller subject. Now we need to extract the
         * credentials from this subject. We will use the SubjectHelper utility class to acheive the same.
         */
        SubjectHelper subjectHelper = new SubjectHelper();
        WSCredential wsCredential = subjectHelper.getWSCredential(subject);
        /*
         * in wsCredential object, the certificate is stored against the property name "wssecurity.identity_value".
         * We need to get the value corresponding to this property name.
         */
        try {
            /*
             * Now, from the WSCredential, make sure that the identity token type is certificate chain. To do this,
             * get the value of the property called "wssecurity.identity_name"
             */
            String identityTypeValue = (String) wsCredential.get(Constants.IDENTITY_NAME);
            /*
             * The identityTypeValue must be “ClientCertificate”. There is no point in continuing the process
             * if the value is not “ClientCertificate”
             */
            boolean isITTCert = Constants.ClientCertificate.equalsIgnoreCase(identityTypeValue);
            /* Get the certificate chain from WSCredential */
            X509Certificate[] certificateChain = (X509Certificate[]) wsCredential.get(Constants.IDENTITY_VALUE);

            if (isITTCert && (certificateChain != null)) {
                token = new IdentityToken();
                byte[] encodedCertificateChain = Util.encodeCertChain(codec, certificateChain);
                token.certificate_chain(encodedCertificateChain);
            } else {
                /*
                 * This else means, either the token type is not set to certificate, or the certificate does not exist.
                 * In either case, we need to throw an exception. This exception will be captured in the catch
                 * block, along with other possible exceptions like CredentialExpiredException and
                 * CredentialDestroyedException.
                 */
                if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                    Tr.debug(tc, "Certificate is not available to continue with Identity Assertion. identityTypeValue=" + identityTypeValue);
                }
                String messageFromBundle = Tr.formatMessage(tc, "CSIv2_CLIENT_ASSERTION_CERTIFICATE_INVALID");
                throw new Exception(messageFromBundle);
            }
        } catch (Exception e) {
            /*
             * We consolidate all possible exceptions here. We log the message and then throw them as a single
             * NO_PERMISSION exception
             */
            if (TraceComponent.isAnyTracingEnabled() && tc.isDebugEnabled()) {
                Tr.debug(tc, "The client cannot create the ITTX509CertChain identity assertion token. The exception message is: " + e.getMessage());
            }
            String messageFromBundle = Tr.formatMessage(tc, "CSIv2_CLIENT_ASSERTION_CANNOT_ENCODE_CC", e.getMessage());
            throw new org.omg.CORBA.NO_PERMISSION(messageFromBundle, SecurityMinorCodes.CREDENTIAL_NOT_AVAILABLE, org.omg.CORBA.CompletionStatus.COMPLETED_NO);

        }
        return token;
    }
1094115
public Subject getSubject(Subject subject) {
		Subject result = null;
		if(isSecurityEnabled) {
			/*
			 * Check if the SIBSecurity Service is loaded. If it is not loaded,
			 * load SIBSecurity Service Invoke the Login method of the
			 * SIBSecurity Service to get the Subject
			 * 
			 * Existing Code 
			 * String userName = getAuthorisationUtils().getUserName(subject); 
			 * SibLoginFactory loginFactory = SibLoginFactory.getInstance(); 
			 * SibLogin myLogin = loginFactory.createNewSibLogin(); 
			 * subject = myLogin.login(theBus, subject);
			 */
		} else {
			/*
			 * Create a JAVA Subject and return it, anyways it does not matter
			 */
			result = new Subject();
		}
		return result;
	}
1175085
private Collection<? extends java.security.cert.Certificate>
        parseX509orPKCS7Cert(InputStream is)
        throws CertificateException, IOException
    {
        Collection<X509CertImpl> coll = new ArrayList<>();
        byte[] data = readOneBlock(is);
        if (data == null) {
            return new ArrayList<>(0);
        }
        try {
            PKCS7 pkcs7 = new PKCS7(data);
            X509Certificate[] certs = pkcs7.getCertificates();
            // certs are optional in PKCS #7
            if (certs != null) {
                return Arrays.asList(certs);
            } else {
                // no crls provided
                return new ArrayList<>(0);
            }
        } catch (ParsingException e) {
            while (data != null) {
                coll.add(new X509CertImpl(data));
                data = readOneBlock(is);
            }
        }
        return coll;
    }
83656
private X509Certificate getClientCert(HttpsExchange pHttpsExchange) {
        try {
            Certificate[] peerCerts = pHttpsExchange.getSSLSession().getPeerCertificates();
            return peerCerts != null && peerCerts.length > 0 ? (X509Certificate) peerCerts[0] : null;
        } catch (SSLPeerUnverifiedException e) {
            throw new SecurityException("SSL Peer couldn't be verified");
        }

    }
1002220
public static String getUniqueKey(X509Certificate cert) {
        // TBD - Would like to use public key instead of subject name, but
        // cert.getPublicKey().getEncoded() appears to return different
        // values for each call, using the same certificate??
        StringBuffer key = new StringBuffer("subjectDN:");
        key.append(cert.getSubjectX500Principal().getName()).append("issuerDN:").append(cert.getIssuerX500Principal().getName());
        // TODO::
        // return Base64Coder.base64Encode(getDigest(key.toString()));
        return null;
    }
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;
    }
963858
public Certificate getMatchingCert(TLSARecord tlsaRecord, List<Certificate> certs) {

        for (Certificate cert : certs) {

            byte[] digestMatch = new byte[0];
            byte[] selectorData = new byte[0];

            try {
                // Get Selector Value
                switch (tlsaRecord.getSelector()) {
                    case TLSARecord.Selector.FULL_CERTIFICATE:
                        selectorData = cert.getEncoded();
                        break;

                    case TLSARecord.Selector.SUBJECT_PUBLIC_KEY_INFO:
                        selectorData = cert.getPublicKey().getEncoded();
                        break;
                }

                // Validate Matching Type
                switch (tlsaRecord.getMatchingType()) {
                    case TLSARecord.MatchingType.EXACT:
                        digestMatch = selectorData;
                        break;
                    case TLSARecord.MatchingType.SHA256:
                        digestMatch = MessageDigest.getInstance("SHA-256").digest(selectorData);
                        break;
                    case TLSARecord.MatchingType.SHA512:
                        digestMatch = MessageDigest.getInstance("SHA-512").digest(selectorData);
                        break;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }

            if (Arrays.equals(digestMatch, tlsaRecord.getCertificateAssociationData())) {
                return cert;
            }
        }

        return null;
    }
613674
def ClientCertFromCSR(cls, csr):
    
    builder = x509.CertificateBuilder()
    # Use the client CN for a cert serial_id. This will ensure we do
    # not have clashing cert id.
    common_name = csr.GetCN()
    serial = int(common_name.split(".")[1], 16)
    builder = builder.serial_number(serial)
    builder = builder.subject_name(
        x509.Name(
            [x509.NameAttribute(oid.NameOID.COMMON_NAME, str(common_name))]))

    now = rdfvalue.RDFDatetime.Now()
    now_plus_year = now + rdfvalue.Duration("52w")
    builder = builder.not_valid_after(now_plus_year.AsDatetime())
    now_minus_ten = now - rdfvalue.Duration("10s")
    builder = builder.not_valid_before(now_minus_ten.AsDatetime())
    # TODO(user): dependency loop with
    # grr/core/grr_response_core/config/client.py.
    # pylint: disable=protected-access
    ca_cert = config_lib._CONFIG["CA.certificate"]
    # pylint: enable=protected-access
    builder = builder.issuer_name(ca_cert.GetIssuer())
    builder = builder.public_key(csr.GetPublicKey().GetRawPublicKey())

    # TODO(user): dependency loop with
    # grr/core/grr_response_core/config/client.py.
    # pylint: disable=protected-access
    ca_key = config_lib._CONFIG["PrivateKeys.ca_key"]
    # pylint: enable=protected-access

    return RDFX509Cert(
        builder.sign(
            private_key=ca_key.GetRawPrivateKey(),
            algorithm=hashes.SHA256(),
            backend=openssl.backend))
395336
private String _getIdFromClientId(String clientId)
  {
    final char separator = getFacesContext().getNamingContainerSeparatorChar();
    int lastIndex = clientId.lastIndexOf(separator);

    String id = null;

    if (lastIndex < 0)
    {
      id = clientId;
    }
    else if (lastIndex < (clientId.length() - 1))
    {
      id = clientId.substring(lastIndex + 1);              
    }
    //else
    //{
      // TODO log warning for trailing colon case
    //}
 
    return id;
  }
1224911
public static String getClientIdFromAuthenticatedProfile(final CommonProfile profile) {
        if (profile.containsAttribute(OAuth20Constants.CLIENT_ID)) {
            val attribute = profile.getAttribute(OAuth20Constants.CLIENT_ID);
            return CollectionUtils.toCollection(attribute, ArrayList.class).get(0).toString();
        }
        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");
            }
        }
    }
332626
public X509Certificate retrieveCertificate() throws java.io.IOException {
        PublicKey publicKey = null;
        KeyStore ks = null;
        try {
            ks = KeyStore.getInstance(_type, _provider);
            InputStream is = openKeyStore(_location);
            if (tc.isDebugEnabled())
                Tr.debug(tc, "successfully opened the keystore at " + _location);
            ks.load(is, _password.toCharArray());
            if (tc.isDebugEnabled())
                Tr.debug(tc, "successfully loaded the keystore at " + _location);
            X509Certificate cert = (X509Certificate) ks.getCertificate(_alias);
            return cert;
        } catch (java.security.NoSuchProviderException ne) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception opening keystore: no such provider.", ne.getMessage());
            throw new IOException(ne.getMessage());
        } catch (java.net.MalformedURLException me) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception opening keystore: malformed URL", me.getMessage());
            throw new IOException(me.getMessage());
        } catch (java.security.KeyStoreException ke) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception opening keystore.", ke.getMessage());
            throw new IOException(ke.getMessage());
        } catch (java.security.NoSuchAlgorithmException ae) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception opening keystore: no such algorithm", ae.getMessage());
            throw new IOException(ae.getMessage());
        } catch (java.security.cert.CertificateException ce) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception getting certificate.", ce.getMessage());
            throw new IOException(ce.getMessage());
        } catch (java.io.IOException ioe) {
            if (tc.isDebugEnabled())
                Tr.debug(tc, "Exception opening keystore.", ioe.getMessage());
            throw new IOException(ioe.getMessage());

        }
    }
1339136
private static String CertificateIDToString(CertificateID certificateID)
  {
    return String.format("CertID. NameHash: %s, KeyHash: %s, Serial Number: %s",
                         byteToHexString(certificateID.getIssuerNameHash()),
                         byteToHexString(certificateID.getIssuerKeyHash()),
                         MessageFormat.format("{0,number,#}",
                                              certificateID.getSerialNumber()));

  }
1317712
public static X500Principal getIssuerX500Principal(X509Certificate cert) {
        try {
            return getX500Principal(cert, true);
        } catch (Exception e) {
            throw new RuntimeException("Could not parse issuer", e);
        }
    }
1341695
public static String getSignCertId() {
		try {
			Enumeration<String> aliasenum = keyStore.aliases();
			String keyAlias = null;
			if (aliasenum.hasMoreElements()) {
				keyAlias = aliasenum.nextElement();
			}
			X509Certificate cert = (X509Certificate) keyStore
					.getCertificate(keyAlias);
			return cert.getSerialNumber().toString();
		} catch (Exception e) {
			e.printStackTrace();
			LogUtil.writeErrorLog("getSignCertId Error", e);
			return null;
		}
	}
93959
public static String getServerId(String clientId) {

        String serverId = clientId;
        if (clientId.contains(CLIENT_ID_SEPERATOR)) {
            serverId = clientId.substring(0, clientId.lastIndexOf(CLIENT_ID_SEPERATOR));
        }
        return serverId;
    }